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?

up vote 1 down vote accepted

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.

  • The threads do not change the object state. They merely access a method that simply creates other objects and then calls an execute method in those objects. My professor calls this the Application Controller Pattern. I'm not sure that is an industry standard term. What are volitile and atomic variables? – Joe Aug 8 '15 at 4:16
  • I'm reading about Atomic and Volatile variable here: docs.oracle.com/javase/tutorial/essential/concurrency/… but any further input is welcome. – Joe Aug 8 '15 at 4:18
  • @Justin volatile and atomics are used for synchronisation if synchronized-blocks are not needed. Methods which do neither set or read instance-variables are probably a candidate for static. – tkausl Aug 8 '15 at 4:19
  • Arguably, using a single object for the multiple threads could be faster, as the memory for that object could get cached. However, as @tcausl points out, correctness is more important than a few milliseconds. – user949300 Aug 8 '15 at 6:04

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.