当前位置: 代码迷 >> J2SE >> 线程安全的set
  详细解决方案

线程安全的set

热度:87   发布时间:2016-04-23 21:30:30.0
求一个线程安全的set
本帖最后由 kolnick 于 2013-11-11 11:22:48 编辑
线程安全的set要用那个

Set set = new HashSet<Player>();
如果使用Set concurrentset=Connections.synchronizedSet(HashSet set)

初始化这个set后是不是就成了线程安全了。

------解决方案--------------------
看下API,是的:
public static <T> Set<T> synchronizedSet(Set<T> s)

Returns a synchronized (thread-safe) set backed by the specified set. In order to guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set.

It is imperative that the user manually synchronize on the returned set when iterating over it:

  Set s = Collections.synchronizedSet(new HashSet());
      ...
  synchronized (s) {
      Iterator i = s.iterator(); // Must be in the synchronized block
      while (i.hasNext())
          foo(i.next());
  }
 

Failure to follow this advice may result in non-deterministic behavior.

The returned set will be serializable if the specified set is serializable.

Parameters:
    s - the set to be "wrapped" in a synchronized set.
Returns:
    a synchronized view of the specified set.
------解决方案--------------------
貌似迭代的时候还是要显示的使用synchronized才能让数据达到线程安全。而且此方法返回的只是一个视图(猜测跟复本差不多的东西)

public static <T> Set<T> synchronizedSet(Set<T> s)返回指定 set 支持的同步(线程安全的)set。为了保证按顺序访问,必须通过返回的 set 完成对所有底层实现 set 的访问。
在返回的 set 上进行迭代时,用户必须手工在返回的 set 上进行同步: 

  Set s = Collections.synchronizedSet(new HashSet());
      ...
  synchronized(s) {
      Iterator i = s.iterator(); // Must be in the synchronized block
      while (i.hasNext())
          foo(i.next());
  }
 不遵从此建议将导致无法确定的行为。 
如果指定 set 是可序列化的,则返回的 set 也将是可序列化的。 


参数:
s - 被“包装”在同步 set 中的 set。 
返回:
指定 set 的同步视图。
  相关解决方案