Thread Static List in Java
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:
|
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 Topics
X2J on the firing line
Time to make a difference in your Java
WebObjects to Cayenne
5 Comments:
Excuse the horrible formatting, it's the first time I use Html2Java..
java.lang.ThreadLocal ??
Heehee :)
Indeed 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.
Must say I agree.
As said, you learn something new every day. I will post a fix to this class soon, using ThreadLocal at its core. :)
Post a Comment
<< Home