Reputation: 11
a part of code like this:
class Test {
private static final Map<String, Class> urlHandlers = new ConcurrentHashMap<String, Class>();
static {
urlHandlers.put(urlRegexA, HandlerA.class);
urlHandlers.put(urlRegexB, HandlerB.class);
...
}
public Handler handle(String url) {
......
if(url match urlRegex) {
Class claz = urlHandlers.get(urlRegex);
//in multi-thread environment, is it thread-safe?
return claz.newInstance();
}
}
}
I want to known whether Class.newInstance() is thread safe? anyone know this?
Upvotes: 0
Views: 1044
Reputation: 2004
Yes this is thread safe as long as the constructor is not doing anything non-thread safe with the static content of the object.
Upvotes: 0
Reputation: 279940
The javadoc states
The class is instantiated as if by a
new
expression with an empty argument list.
So it is equivalent to doing
new YourClass();
So it depends entirely on if your YourClass
constructor is thread safe.
Upvotes: 7