Is it possible to add software enforced copy-on-write for multithreaded applications in Java? By this I mean threads having a reference to the same object, but when one thread attempts to modify it, the object pointed to is copied and the reference is adjusted to point to that copy.
Java - multithreaded copy-on-write
551 Views Asked by user973758 AtThere are 3 best solutions below

The only implementation I know is the
java.util.concurrent.CopyOnWriteArrayList
see
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html
and the related Set class
java.util.concurrent.CopyOnWriteArraySet
and finally
org.apache.mina.util.CopyOnWriteMap
but it depends from your need.

If your question is,
is it possible to enforce copy-on-write behavior across the board for an entire Java runtime
then the answer is,
No, there is no such general capability in Java.
Actually, I think the closest you can possibly get to that goal is using Clojure. All its default data structures are copy-on-write internally, and on the outside they are simply immutable objects.
The references you talk about are called, surprisingly, ref
s and they support full in-memory transactions. A simpler kind of a reference is atom
, which fits your description 100%.
The whole Core API is devoted to elegant and epressive manipulation of these structures in a thread-safe, lock-free manner.
Yes. Lazy copying is easy to implement, but you would generally have to do it yourself.