【发布时间】:2011-10-20 03:25:58
【问题描述】:
我正在尝试找出这段代码中是否存在任何竞争条件。如果关键不是'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。 -
不管怎样,你要找的功能正是
ThreadLocal提供的功能:download.oracle.com/javase/7/docs/api/index.html?java/lang/…
标签: java multithreading synchronization race-condition