开发者

Thread unique data

开发者 https://www.devze.com 2023-03-11 03:36 出处:网络
I need to maintain a hashmap which should be public to all the threads executing. For exa开发者_JAVA技巧mple the hashmap updated by one particular thread should be available to the other threads also

I need to maintain a hashmap which should be public to all the threads executing. For exa开发者_JAVA技巧mple the hashmap updated by one particular thread should be available to the other threads also and vice versa. Please suggest me with the implementation in Java.

The main program contains the hashmap. From this main thread i will be trigerring many threads. Each thread should access the same hashmap available in the main program.

Thanks in advance.


look here for all thread safe data structures... http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html

i guess you need a concurrent hash map. If you can change your map to a list, you can use CopyOnWriteArrayList which allows a highly efficient thead safe way to read write to a list.


The problem in Java is not sharing a variabile between multiple threads: you can do it easily just passing the reference to the object to the thread. Please keep in mind that you need to be sure to access it safely... Concurrent modification can be a trouble. I suggest you to check java concurrency tutorial, it is a very good starting point: http://download.oracle.com/javase/tutorial/essential/concurrency/index.html


Dont make it static - that way lies concurrency problems, and makes your code less testable. Instead, use a concurrent hash map:

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html

And pass a reference to it to each thread that needs it.


The hashmap can be made static and can be accessed in the threads using the ClassName. I guess it is one solution but concurrency might be a problem. Expecting anyother good solution regarding this issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消