• Post Reply Bookmark Topic Watch Topic
  • New Topic

Which is better either creating two objects for two threads or one object for two threads?  RSS feed

 
Rajeev Srikhar
Ranch Hand
Posts: 75
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the below program, I'm calling method1() of SampleClass from two threads. So, basically I have created two objects for each thread and called the method1(). I have also seen the scenario of calling static method from two different threads.

Now I want to know what will happen If I use only one object for two threads (I have mentioned in comment) for calling a method(even static method also). I have compiled and but didn't understand any difference.

So, which is better, creating two objects for two threads or one object for two threads?

 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I think you are asking the wrong question. Do you need one object or two objects?
Also: What does that method do? Does it need locking?
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I create one object per task.

You shouldn't even be using threads at all. Instead, you should submit tasks to an executor service:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!