Limitations¶
The cloner copies the state an object keeps in its fields. State which lives elsewhere (in a running thread, the operating system, native memory, a registry of another object) cannot be copied. This page lists what the cloner does not copy, what it shares instead, and what it cannot detect.
Not copied: cloning fails¶
A graph which reaches one of these fails with UncopyableObjectException until the configuration decides what the clone
gets: CopyAction.ORIGINAL shares the object, CopyAction.CLEAR leaves null, a copier creates something else (see
JDK types). The exception names the type and the objects holding it; the
recursive mode names the whole path from the root.
| Kind | Types |
|---|---|
| threads | Thread (also virtual threads), ThreadGroup; a lock of java.util.concurrent held by a thread |
| running computations | ExecutorService (also ForkJoinPool), Future and CompletionStage (CompletableFuture, FutureTask, SwingWorker), Timer; Kotlin coroutine jobs, Scala futures |
| references | WeakReference, SoftReference, PhantomReference, ReferenceQueue, Cleaner |
| files and streams | FileDescriptor, FileInputStream, FileOutputStream, RandomAccessFile, channels, selectors, file locks |
| network | Socket, ServerSocket, DatagramSocket, socket channels |
| processes | Process |
| databases | JDBC Connection, Statement, ResultSet (not RowSet), PooledConnection |
Many other objects fail because they hold one of these:
WeakHashMapand caches on references: descriptors ofjava.beans, caches of fonts (TextLayout), the AWTToolkit, theMBeanServer;- objects which free native memory by a cleaner: direct and mapped
ByteBuffers,Deflater,Inflaterand the zip and gzip streams; System.out,System.errandSystem.in, which write to and read from file streams, and logging handlers writing to them;- AWT and Swing components, which reach the thread group of their
AppContext;Graphics2D; HttpClient, URL connections, JFR recordings;- connection pools and everything which reaches them: data sources, entity managers and sessions of JPA, transaction managers.
Shared, not copied¶
These are not copied, the clone references the originals: immutable values, identities of the JVM (class loaders,
reflection objects, method handles, ThreadLocal and ScopedValue keys, file systems, ...), canonical constants
compared by identity, arenas of native memory, loggers, SecureRandom, ResourceBundle and the objects of the cloner.
The full list is in JDK types. Changes made through a shared object are seen by the original and the
clone.
What the cloner cannot detect¶
The cloner decides by types. Objects which look like plain data are copied field by field, even when that is wrong:
- Native resources kept as numbers. An object of a native library which keeps a pointer or a handle in a
longfield is copied with the number: the copy and the original share the resource, and closing both may free it twice and crash the JVM. Share such a type withCopyAction.ORIGINALor give it a copier. - Canonical instances of your classes. A singleton kept by
readResolve()or a constant compared by==gets a second instance in the clone. Share it withtypeAction(..., CopyAction.ORIGINAL)orobjectAction(). - Identity. Every copy is a new object:
System.identityHashCode()differs, keys of anIdentityHashMapare copies, and the clone is not registered where the original is (listeners added to a global registry, caches keyed by the original object). - State outside the object. Static fields belong to classes, values of a
ThreadLocalbelong to threads: neither is copied. A monitor (synchronized,wait()) is not part of the state either, the clone starts unlocked. - Serialization hooks.
writeObject(),readObject()andreadResolve()are not called, see JDK types. - Empty arrays used as locks. Arrays of no elements are shared: nothing in them can change, and an empty array is
often a marker compared by identity (a
Throwablekeeps one until its stack trace is built). An object which synchronizes on its ownnew Object[0]then shares the lock with its clone. Give such a field a new value withfieldValue(...)in the configuration, e.g..fieldValue(Counter.class, "lock", () -> new Object[0]).
Objects of frameworks¶
Beans behind proxies, entities managed by a persistence context and other objects of frameworks reach their containers, connection pools and caches, so cloning them fails:
- a Spring bean behind a proxy (
@Transactional, a Spring Data repository) or a CDI bean behind a client proxy reaches the whole application context; a bean without a proxy is copied, and its copy no longer is the bean; - an entity of Hibernate in a persistence context reaches the session through its collections and lazy proxies, and on Quarkus through the fields added by the bytecode enhancement; a detached entity is copied.
Share beans and infrastructure by their types, clear the session of entities:
Cloner cloner = Cloners.builder()
// Spring: proxies of beans; CDI: io.quarkus.arc.ClientProxy and the like
.typeAction(Predicates.subclass(SpringProxy.class), CopyAction.ORIGINAL)
.typeAction(Predicates.subclass(DataSource.class), CopyAction.ORIGINAL)
.typeAction(Predicates.subclass(EntityManager.class), CopyAction.ORIGINAL)
// a snapshot of a managed entity: its collections and lazy proxies get no session
.typeAction(Predicates.subclass(SharedSessionContractImplementor.class), CopyAction.CLEAR)
.build();
A clone of a managed entity is not managed and cannot be persisted as a new entity while it keeps the persistent
collections of Hibernate: a copier of PersistentBag, PersistentSet and
PersistentList which creates JDK collections makes it a plain object.
Toolsets¶
Copying the internals of JDK classes needs their packages open to the cloner. The default toolset opens them; a toolset which only uses reflection fails on JDK classes unless the application opens the packages, see Toolsets.