我是靠谱客的博主 帅气花生,这篇文章主要介绍synchronized - 不要锁常量,现在分享给大家,希望可以做个参考。

synchronized - 不要锁常量

It is not recommended to use objects which are pooled and reused, if you do so there is a chance of getting into deadlock condition down the line.

不要尝试使用池化或者重用的对象,有可能会造成死锁或者竞态条件

有些时候使用 synchronized 时会这样写, 这样的不建议的:


String rs1 = "lock";
String rs2 = "lock";
public void hi(){
synchronized(rs1){
//to do sth...
}
}
public void hi2(){
synchronized(rs2){
//to do sth...
}
}
或者
public void hi3(){
synchronized(rs1.intern()){
//to do sth...
}
}

推荐做法

使用 private final 对象, 如


private final lock = new Object('lock');
public void hi4(){
synchronized(lock){
//to do sth...
}
}

最后

以上就是帅气花生最近收集整理的关于synchronized - 不要锁常量的全部内容,更多相关synchronized内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(104)

评论列表共有 0 条评论

立即
投稿
返回
顶部