Meaningless Drivel is fun!*
The moose likes Java in General and the fly likes Need solution for multiple threads. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Need solution for multiple threads." Watch "Need solution for multiple threads." New topic
Author

Need solution for multiple threads.

john sal
Ranch Hand

Joined: Jul 30, 2010
Posts: 93
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

Joined: Oct 27, 2005
Posts: 19679
    
  18

Use ThreadLocal<Map<String,X>>. This allows you to have one map for each thread:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Aditya Jha
Ranch Hand

Joined: Aug 25, 2003
Posts: 227

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

Joined: Jul 30, 2010
Posts: 93
@Aditya : I wanted each thread to have its own copy.

@Rob : Thanks it worked..
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19679
    
  18

You're welcome.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Need solution for multiple threads.