Reputation: 1675
public class VPattern implements Pattern
{
private final TokenKey tokenKey_;
private final String tokenLabel_;
private Integer cachedHashCode_ = null;
private ThreadLocal<Token> token_ = new ThreadLocal<Token>();
...
}
I am reading this piece of code and don't understand the use of ThreadLocal here. Is that because ThreadLocal is used to ensure the 'token_' object will be thread safe in any concurrent situation? If that's the case, why TokenKey and Integer are not thread safety protected? I know that "String" is always thread safe.
Upvotes: 0
Views: 593
Reputation: 138
In general, ThreadLocal
can provide different objects for each working thread. So if the given object is not thread-safe nor singleton, it can be stored in ThreadLocal
variable. Then every thread may get and safely use different instance of your class. You can treat it like a map, where the current thread is a key and the actual object is a value.
Let's assume there are two threads working at the same time and sharing one VPattern
object. If threads get tokenKey_
or tokenLabel_
, then both will get the same instances. But if both threads call token.get()
, then they will get different instances of Token
type (if initialized previously, see: set
method and withInitial
static factory method).
Unfortunately it's hard to say what's the purpose of ThreadLocal
in your case because it highly depends on the context. Seems that Token
objects cannot be shared by different threads (each thread should have own token).
You can read more about ThreadLocal
in javadoc or here: https://www.baeldung.com/java-threadlocal
Upvotes: 1
Reputation: 8204
Every thread gets its own Token
even if they share the same instance of VPattern
. Possibly this was done because Token
is not thread safe and VPattern
wants to avoid synchronizing access to the Token
instance. tokenKey_
is final so don't have to worry about the field changing, and maybe it's thread safe on its own. tokenLabel_
is also final and strings are immutable so no issue there. cachedHashCode_
is the odd one out here; is access to it protected somehow? It's hard to say what's going on without seeing the rest of the class.
Upvotes: 2