0

这样加锁会导致什么问题?

 2 years ago
source link: https://www.v2ex.com/t/816914
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

这样加锁会导致什么问题?

  kikione · 19 小时 23 分钟前 · 1348 次点击
String lock = userId;
synchronized(lock.intern()){
}

userId 是唯一的。

这样加锁常量池的数据会很庞大,会被 GC 及时回收吗
9 条回复    2021-11-21 20:21:26 +08:00

sagaxu

sagaxu   17 小时 52 分钟前 via Android

gc 能回收,但 rootset 会很大,stw 更久

fkdog

fkdog   17 小时 51 分钟前

你这有问题。
你如何保证值相同的 userId 字符串对应的是同一个对象?

fkdog

fkdog   17 小时 46 分钟前

Integer a = 999992;
System.out.println(a.toString()==a.toString());

你 run 一下就会发现这个结果在 jdk1.8 以上就是 false 。
不是所有字符串都会建在常量池里

kikione

kikione   17 小时 41 分钟前

@fkdog string intern() 函数 强制刷到常量池

SachinBeyond

SachinBeyond   17 小时 32 分钟前

Constant expressions of type String are always "interned" so as to share unique
instances, using the method String.intern.

fkdog

fkdog   17 小时 27 分钟前

@kikione intern 能解决单机上边的问题,那么如果机器不只一台呢?

moshiyeap100

moshiyeap100   15 小时 20 分钟前

这样加锁在单机上是没有问题的,但是在多台机器上就不行了,多台机器你可能需要一个分布式锁,可以通过 redis setnx 来解决这个问题。

qaqLjj

qaqLjj   11 小时 5 分钟前

这样写代码不优雅,字符串常量池本来是用来存储编译时可以确定的字符串常量的,你这样写相当于运行时往常量池里放东西,建议使用 new Lock(userId); 代替

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK