Reputation: 44094
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?
Upvotes: 5
Views: 361
Reputation: 86333
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 volatile
forbids just that behaviour - the JVM will have to explicitly and atomically access a volatile
field each and every time.
Upvotes: 3
Reputation: 11775
To have a shared state between multiple threads - you'll have to coordinate access to it using some synchronization mechanism - volatile, synchronization, cas. I'm not sure what you expect to hear on "performance implication" - it will depend on the concrete scenario and context. In general you will be paying some price for having to coordinate access to the shared object by multiple threads.
Upvotes: 1
Reputation: 23268
If data is being read there is no implication because multiple threads can access the same memory concurrently. Only when writing occurs because of locking mechanisms will you receive a performance hit. Note on volatile (cant remember if its the same in Java as C) but its used for data that can change from underneath the program (like direct addressing of data in c) or if you want atomicity for your data. Copying the data would not make a difference in performance but would use more memory.
Upvotes: 1