Java Performance – Sharing Single Object with Multiple Threads

javamultithreadingobjectperformance

In Java, if I create an object that has a method to do something, and I pass that object to multiple threads which call the method, is there a performance difference from creating an individual instance of that class in each thread?

In other words, does it cause a bottleneck for thousands of threads to be trying to access the same object's methods at the same time?

I don't know a ton about memory or how a processor works, but it seems to me that the single object option would have a single instance in memory, and thousands of threads could be trying to utilize that code at once. With a single core processor, this might be irrelevant since the processor can only be doing one thing. But in a multi-core setup, could multiple threads all utilize the code of a single object in memory at the same time?

Best Answer

It depends.

Without any synchronisation and without volatile or atomic variables it does not make a difference.

However, if those methods change the object-state you will need some form of synchronisation, otherwise multiple threads would overwrite changes from other threads or just not see the change. Synchronisation is not free, volatile variables and atomics are not free, so if you use one of them, it makes a difference, yes.