JDK types¶
The cloner knows how to treat the types of the JDK; your configuration overrides it.
Shared: immutable values¶
The clone references the same instances: strings, boxed primitives, BigInteger, BigDecimal, java.time values,
UUID, URI, URL, File, Path, Locale, Currency, Charset, ZoneId, Pattern, the empty collections of
Collections, enums and Class objects.
Constants which the JDK compares by identity are shared as well, a copy would not equal them: TextAttribute,
Format.Field, Character.UnicodeBlock, ByteOrder, RenderingHints.Key and its values, StyleConstants,
HTML.Tag, HTML.Attribute, CSS.Attribute, the attributes of javax.print and logging Levels.
Shared: identities of the JVM¶
Copies of these would be other objects, so the clone references the originals: class loaders, modules, reflection
objects (Method, Field, ...), method handles, call sites, var handles, ThreadLocal, ScopedValue and
ClassValue keys, process handles, Runtime, Unsafe, packages, protection domains, file systems and their
providers, security providers, ThreadLocalRandom and the managed beans of the platform (MemoryMXBean, ...).
Also shared, though they have state:
- loggers of
java.util.logging,System.Logger, SLF4J, Log4j, Commons Logging and JBoss Logging: a logger is a name in the configuration of the logging, a copy would not be configured; SecureRandom: a copy would repeat the numbers of the original, e.g. the same keys and nonces; it is thread safe;ResourceBundle: loaded once and cached by the JDK, e.g. the messages of aCachedRowSet;- arenas of native memory (
Arena), the scopes of memory segments, linkers and symbol lookups: a copied arena would free the same memory twice. A nativeMemorySegmentis copied as a view of the same memory, a heap segment with its array; - the objects of the cloner itself: cloners, toolsets, copiers and policies, e.g. a cloner kept by a service of the graph.
Kotlin and Scala singletons (object declarations) are shared too, see Kotlin and
Scala, and so are Groovy meta classes.
Lambdas¶
A lambda or a method reference which captures nothing (String::trim, x -> x + 1) has no state and is shared. A
capturing lambda is created again from the copies of the captured values, so the clone does not work with the objects
of the original:
class Order {
final List<Line> lines = new ArrayList<>();
final Supplier<Integer> count = () -> lines.size(); // captures this
}
Order clone = Cloners.clone(order);
clone.count.get(); // counts the lines of the clone
Lambdas of the JDK (e.g. Comparator.comparing(...)) need their packages open to the cloner, which the default
toolset does. If the captured values cannot be read, or an instance of another hidden class has state, cloning fails
with UncopyableObjectException; CopyAction.ORIGINAL shares such a lambda.
Not copied: live objects¶
Threads, references, open files, sockets, processes, executors and futures, JDBC connections, statements and result
sets: a copy would not work, or would share the resource of the original. Cloning fails with
UncopyableObjectException unless the configuration decides:
Cloner cloner = Cloners.builder()
.typeAction(Predicates.subclass(Thread.class), CopyAction.ORIGINAL)
.fieldAction(Job.class, "executor", CopyAction.CLEAR)
.build();
A RowSet is copied, but a CachedRowSet filled by populate() keeps the result set it was filled from; clear it:
.fieldAction(rowSet.getClass(), "resultSet", CopyAction.CLEAR).
The full list, the objects which fail because they hold one of these, and what the cloner cannot detect are in Limitations.
Copied by their own clone()¶
Date, GregorianCalendar, BitSet, EnumSet, SimpleDateFormat, DecimalFormat and other java.text formats.
Rebuilt collections¶
ArrayList, LinkedList, ArrayDeque, Vector, Stack, HashSet, LinkedHashSet, HashMap, LinkedHashMap,
Hashtable, ConcurrentHashMap, IdentityHashMap, EnumMap and the immutable collections of List.of(),
Set.of(), Map.of() are rebuilt from the copied elements. Hash-based collections are rebuilt after their elements
are copied, when the hash codes of the copied elements are known. A rebuilt collection gets the modification counter
of the original, so its views and iterators copied with it keep working. Other collections, e.g. TreeMap, are copied
by their fields.
Records¶
Records are created by their canonical constructors from the copied components, so the checks of the constructor run for the clone too. A record in a reference cycle which needs itself ready is reported, see Modes.
Arrays¶
Arrays of primitives and enums are copied by clone(), other arrays element by element. Arrays of no elements are
shared: nothing in them can change, and an empty array is often a marker compared by identity, e.g. the stack trace of
a Throwable which is not built yet.
Classes with serialization hooks¶
The cloner copies fields; it does not call writeObject(), readObject() or readResolve(). A class which keeps a
single or canonical instance by readResolve() gets a second instance in the clone unless it is shared:
A class which rebuilds a cache or an invariant in readObject() needs a custom copier
or a value of the field for the cache. To clone by Java serialization itself, use
SerializationUtils.clone() of Apache Commons Lang.