What is the problem in this case:
private static final Integer LOCK=0;
synchronized(LOCK){
//work
}
This is advised to be not a recommended monitor to lock on.
This is advised to be not a recommended monitor to lock on.
private static final Integer LOCK=0;
is the same as
private static final Integer LOCK=Integer.valueOf(0);
and Integer.valueOf(0)
is cached by specification .
What this means is that anybody else can also get Integer.valueOf(0)
and synchronize on it; so you might get unexpected contention (at best) or deadlocks (at worst).
You can either use new Integer(0)
, which is not a cached instance; or just use new Object()
, since the fact it's an Integer
is irrelevant if it is only used as a monitor.
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.