我正在尝试确定这段代码是否会出现竞争条件。如果键不是'Thread.currentThread',那么我会认为会出现竞争条件。但是由于线程本身就是键,所以如何可能出现竞争条件呢?没有其他线程可能会更新HashMap中的相同键!
public class SessionTracker {
static private final Map<Thread,Session> threadSessionMap = new HashMap<Thread,Session>();
static public Session get() {
return threadSessionMap.get(Thread.currentThread());
}
static public void set(Session s) {
threadSessionMap.put(Thread.currentThread(),s);
}
static public void reset() {
threadSessionMap.remove(Thread.currentThread());
}
}
set
,然后稍后另一个线程调用size()
,它可能会得到0作为结果。 - Bruno ReisThreadLocal
提供的,具体请参考官方文档:http://download.oracle.com/javase/7/docs/api/index.html?java/lang/ThreadLocal.html - Bruno Reis