Let’s say we have a Java object that has only primitive fields marked as final and as such is immutable.
Now several threads need the information contained in this object to do their work, so one has two choices:
- Hand the reference to a single instance to all threads.
- Create a clone/copy of the object for each thread.
Essentially the question boils down to this: Internally, does the JVM gain any benefits from copying the object, for example because reads become more efficient, or would it be a mere waste of memory because it doesn’t matter?
Technically, if said threads run on different CPU cores, there will be multiple copies of the single object anyway, due to caches. As such, there is no real benefit to cloning the object, and in fact may hurt performance if multiple threads end up on the same processor.
In fact, cloning an immutable object seems counter-productive, since in this situation immutability serves the purpose of creating a shared, read-only object for all threads to use safely.