I have a class that can be instantiated only once for any given thread, through the use of a ThreadLocal
, for instance:
public class MyClass {
private static final ThreadLocal<MyClass> classInstance =
new ThreadLocal<MyClass>() {
@Override protected MyClass initialValue() {
return new MyClass();
}
};
private MyClass() {
}
public static MyClass getInstance() {
return classInstance.get();
}
}
Now, I want these thread-specific instances to be accessed by another thread, so I end up with that kind of solution: https://stackoverflow.com/a/5180323/1768736
This solution is to use a Map
(I would go for a ConcurrentHashMap
), using as key a Thread-specific ID (for instance, a Map<long, MyClass>
). I was considering to use Thread.currentThread().getId()
as a key (providing some mechanisms to deal with the fact that a Thread ID can be reused).
But it means that I need to expose this Thread ID, for instance:
public class MyClass {
...
public long getId() {
//return the key associated with this MyClass instance in the Map.
//in my case, this would be the ID of the Thread
}
public static MyClass getMyClass(long threadId) {
//allow a Thread to access the MyClass instance of another Thread by providing an ID,
//in my case, that would be the Thread ID
}
}
So my question is: is it a bad practice to expose the ID of a Thread (the one returned by Thread.getId()
), or do I have nothing to worry about? I don't know why, but my gut tells me I shouldn't do that.