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?
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.
是的,只要构造函数对对象的静态内容不执行任何非线程安全的操作,这是线程安全的。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.