We all know what a
Thread is and what
Static means, and
how they collide. For a quick example: I have an event listener method where I want it to have a stopping condition for a suspected recursion. What I want to do is use a Collection of the items I've already received, and check for each call of the listener method if the calling item is already inside the Collection.
I can't add a Collection to the method signature because I can't change it (it came from a listener interface), so using a static Collection in my implemented handler comes to mind. However, what if
the event was called from different threads at the same time?
This is, like most of my posts, not a new thing. It's just
a nice tool I decided to share its simple code with; Enjoy it or diss it. Here goes:
public class ThreadStaticCollection<T> implements Collection<T>{
private static Map<Thread, Collection<T>> threadMap =
new TreeMap<Thread, Collection<T>>();
private synchronized Collection<T> get() {
Collection<T> res = threadMap.get(Thread.currentThread());
if (res == null) {
res = new LinkedList<T>();
threadsMap.put(Thread.currentThread(), res);
}
return res;
}
private synchronized void purge() {
if (get().isEmpty()) {
thradMap.remove(get());
}
}
public boolean add(Object item) {
return get().add(item);
}
// Goes on..
public boolean remove(Object item) {
boolean b = get().remove(item);
purge();
return b;
}
// Goes on..
}
|
Java2html
|
The
get() method will
fetch or create the Collection currently available for the current Thread. The Collection interface is implemented by
delegating all tasks to what is returned from get().
If items are
removed from the Collection,
a call to purge() should occur so that the Collection instance could be removed from the static Map. Also notice that both the
purge and the
get are
synchronized for obvious reasons.
Interesting TopicsX2J on the firing lineTime to make a difference in your JavaWebObjects to Cayenne
Excuse the horrible formatting, it's the first time I use Html2Java..
ReplyDeletejava.lang.ThreadLocal ??
ReplyDeleteHeehee :)
ReplyDeleteIndeed I never assumed to know everything. :)
I guess you learn something new every day, and I learned about ThreadLocal today. The idea of the ThreadStaticCollection was to provide a Collection interface without worrying about it being "ThreadLocal" underneath - Indeed, it can be reimplemented using ThreadLocal easily and I will do so.
Thank you annonymous!
being a JDK class, ThreadLocal has the advantange that it can hack into Thread. it will perform better because it doesn't need synchronization.
ReplyDeleteMust say I agree.
ReplyDeleteAs said, you learn something new every day. I will post a fix to this class soon, using ThreadLocal at its core. :)