Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the performance implication of sharing objects among threads?

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?

like image 506
Bart van Heukelom Avatar asked Jul 01 '11 08:07

Bart van Heukelom


2 Answers

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.

like image 194
thkala Avatar answered Sep 24 '22 05:09

thkala


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.

like image 21
Jesus Ramos Avatar answered Sep 23 '22 05:09

Jesus Ramos