Many articles on internet specifies that using String.intern()
in multi threading is bad but I really could not understand why it is bad.Using String.intern()
always return a unique string from string pool,isn't it?
If that is not the case then Is JVM string pool thread local? If not then why using String.intern()
for synchronizing in multithreaded environment is considered bad? So in the following use case, wouldn't it solve the synchronization issue:
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
}
}
}
Here I am synchronizing both the methods based on one common string id.I want to execute entire method as one transaction(preventing other method to even read the database).But doing this at database level is causing deadlock(not preventing read access). Is synchronizing using string intern in this case has any bottleneck or deadlock issue? Is there any other approach to solve the issue? forgive me for any inconvenience or bad formatting.
No, interned strings are available globally in the JVM.
As it says in this answer:
synchronizing on intern strings is actually a really bad idea - partly because creating intern strings is permitted to cause them to exist in perpetuity ...
i.e. you might create an ever-growing number of locks.
... and partly because if more than one bit of code anywhere in your program synchronizes on intern strings, you have dependencies between those bits of code, and preventing deadlocks or other bugs may be impossible.
The strings are visible throughout the JVM, so anything, anywhere can attempt to synchronize on the same string, causing hard-to-reproduce, hard-to-fix problems.