File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes ThreadLocal & static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "ThreadLocal & static" Watch "ThreadLocal & static" New topic

ThreadLocal & static

Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 782


I have a Util class with a static method process which will accept a tree data structure (Composite Pattern). The problem is I want to prevent the possibility of a StackOveflow if the user of this method is stupid enough to introduce loops within the tree.

What I want to do is to keep a list of nodes which I have already visited. So during the navigation down the tree, I will add the visited nodes to this list.

I want to use a ThreadLocal variable to keep the list of visited nodes.
The issue here is that the variable has to be declared static.

I don't understand the semantics of static ThreadLocal variable.
Will different threads that call the process method be using the
same ThreadLocal variable ? Are there any huge design flaws ? Thanks all

Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
All threads will be using the same ThreadLocalList object. But the whole point of ThreadLocal is that each thread gets its own value to work with. Therefore, the different threads will not see or corrupt each others' lists.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
I agree. Here's the link:
subject: ThreadLocal & static
It's not a secret anymore!