Hi Guys, I will try to explain the quetion by taking following 3 cases. CASE I: I was using shared lock for synchronization using something like this:
private static final String SHARED_LOCK = "shared_lock";
private static int i = 0;
private static int j = 0;
void increment() {
synchronized (SHARED_LOCK) {
i++;
j++;
}
}
And it is working fine.
CASE II: Now What I have changed here is instead of using shared lock I thought of using a local lock by doing something like this:
private static int i = 0;
private static int j = 0;
void increment() {
final String LOCAL_LOCK = "local_lock";
synchronized (LOCAL_LOCK) {
i++;
j++;
}
}
And I found that code was still working fine that is synchronization was still working.
CASE III: However when I changed the local locl to this:
final String LOCAL_LOCK = new String("local_lock");
then the synchronization went away. So it looks like that in CASE II the local lock was able to provide synchronization because of interning of String literals that Java does for us automatically but in CASE III as I was explicitly creating a new String everytime thus synchronization was not happening.
So coming back to my original question. Does anyone feels that CASE II is not the right way to achieve synchronization? If yes could you please also mention why?
Thanks in advance, SacTiw.