互联网上的许多文章都指定String.intern()
在多线程中使用不好,但我真的不明白为什么它不好。使用String.intern()
总是从字符串池返回一个唯一的字符串,不是吗?如果不是这种情况,那么JVM 字符串池线程是本地的吗?如果不是,那么为什么String.intern()
在多线程环境中使用同步被认为是不好的?所以在以下用例中,它不会解决同步问题:
Method1 {
synchronized(Interned string) {
select method {
select query to databse
}
...some processing...
update method {
update query to database
}
}
}
Method2 {
synchronized(Interned string) {
select method {
select query to databse
}
.....some processing....
insert method {
insert query to database
}
}
}
在这里,我基于一个公共字符串 id 同步这两种方法。我想将整个方法作为一个事务执行(防止其他方法甚至读取数据库)。但是在数据库级别执行此操作会导致死锁(不会阻止读取访问)。在这种情况下使用字符串实习生进行同步是否存在瓶颈或死锁问题?有没有其他方法可以解决这个问题?如有任何不便或格式错误,请原谅我。