开发者

Share thread-safe set over multiple classes

This question relates to one of my previous ones.

I'd like to have a thr开发者_运维问答ead-safe set which I can access and modify in various classes, some Runnables and some not.

According to the JavaDoc I'm getting a thread-safe set with

  Set s = Collections.synchronizedSet(new HashSet());

But now I want to share this set througout my program. Is it possible to put it in the application context and initialize it in an XML?


If you have deemed it to be adequate for passing into your Runnable's, then I see no reason why it wouldn't be suitable for your application context as well.

I should note that as a general rule, global variables open the door to very difficult to track down bugs, and you should strongly consider alternatives to having a single, application-wide context that can be modified at run-time. (If it's only ever read, never written, you don't have a problem at all, and I'd consider using Collections.unmodifiableSet(generatedHashset); instead.


If you need to access and modify the set from multiple threads, you need a thread-safe set.

In most cases, ConcurrentHashMap is my preferred choice. Starting from Java 6, it's a synch to create a set out of a map by using Collections.newSetFromMap().

Set<Type> concurrentSet = Collections.newSetFromMap(new ConcurrentHashMap<Type,Boolean>());


As glowcoder mentioned putting this set to application Context invites data consistency problem. if any updates from multiple threads access applicationContext to modify set , then the CopyOnWriteArrayList or CopyOnWriteArraySet. They create a new list/set on updates to avoid concurrent modification exception.

CopyOnWriteArraySet .


A synchronized set does is not always enough for thread safety. It just protects individual method calls.

If you need to iterate over the set, then you'll have to add extra synchronization or deal with ConcurrentModificationExceptions.

Having lots of classes using a global set, will increase the chances of dead locks.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜