I know that reading from a single object across multiple threads is safe in Java, as long as the object is not written to. But what are the performance implications of doing that instead of copying the data per thread?
Do threads have to wait for others to finish reading the memory? Or is the data implicitly copied (the reason of existence of volatile)? But what would that do for the memory usage of the entire JVM? And how does it all differ when the object being read is older than the threads that read it, instead of created in their lifetime?
If you know that an object will not change (e.g. immutable objects such as String or Integer) and have, therefore, avoided using any of the synchronization constructs (
synchronized,volatile), reading that object from multiple threads does not have any impact on performance. All threads will access the memory where the object is stored in parallel.The JVM may choose, however, to cache some values locally in each thread for performance reasons. The use of
volatileforbids just that behaviour – the JVM will have to explicitly and atomically access avolatilefield each and every time.