• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need solution for multiple threads.

 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What should be the solution for the following scenario?



A a = new A();
thread 1 {
a.foo();
a.getMap();
}

thread 2 {
a.foo();
a.getMap();
}

thread 3 {
a.foo();
a.getMap();
}

.....
.....

class A is accessed by multiple threads. When multiple threads operate over the same
instance of class A then I am facing concurrent modification exception which is quite obvious.

Alteratne solution is to use hashtable or some synchronization mechanism but it will be a performace hit because all the other threads have to wait.

More over I want if thread should get the same values that has been set in the map by that thread only.

Is there any alternate approach for the same or any other data structure from java 5 concurrency so that the performance hit is minimal?
 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use ThreadLocal<Map<String,X>>. This allows you to have one map for each thread:
 
Aditya Jha
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's your requirement here?

If you want the threads to have their own copy of map (and hence no synchronization needed), you can use Rob's method or even simpler - just instantiate class A once per thread.

Since your original code shared the instance of class A among threads, I assume you want all the threads to work on the same map. In this case, how do you want threads to behave at the time of loading of map? Should they all load key-values in the same map simultaneously? If yes, think about colliding keys. If not, it would require a bit of synchronizations. You can't avoid it altogether.
 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Aditya : I wanted each thread to have its own copy.

@Rob : Thanks it worked..
 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic