String Literal as Sychronization Lock
String Literal are unique. When we create another string with same literal, the second reference will point to first object itself.
Please pay attention while using Strings as Synchronization locks.
package com.sudheer.springbrain; public class SringLiteralThread implements Runnable { String lock; SringLiteralThread (String lock) { this.lock = lock; } @Override public void run() { System.out.println(Thread.currentThread() + " : Trying lock"); synchronized (lock) { System.out.println(Thread.currentThread() + " : Acquired lock"); if (true) { while (true) { // Some infinite loop } } } System.out.println(Thread.currentThread() + " : Done"); } public static void main(String[] args) { String lock = "abc"; String lock2 = "abc"; //String lock = new String("abc"); //String lock2 = new String("abc"); Thread t1 = new Thread(new SringLiteralThread(lock)); t1.start(); Thread t2 = new Thread(new SringLiteralThread(lock2)); t2.start(); } } Output: Thread[Thread-0,5,main] : Trying lock Thread[Thread-0,5,main] : Acquired lock Thread[Thread-1,5,main] : Trying lockIn above, there lock and lock2 are different strings, there are referenced to same string literal. Eventually resulting the second thread to not enter the synchronized blocked being occupied by first thread. Where as new String() for same string literal will yield dirrent objects.
package com.sudheer.datastructures; public class SringLiteralThread implements Runnable { String lock; SringLiteralThread (String lock) { this.lock = lock; } @Override public void run() { System.out.println(Thread.currentThread() + " : Trying lock"); synchronized (lock) { System.out.println(Thread.currentThread() + " : Acquired lock"); if (true) { while (true) { // Some infinite loop } } } System.out.println(Thread.currentThread() + " : Done"); } public static void main(String[] args) { //String lock = "abc"; //String lock2 = "abc"; String lock = new String("abc"); String lock2 = new String("abc"); Thread t1 = new Thread(new SringLiteralThread(lock)); t1.start(); Thread t2 = new Thread(new SringLiteralThread(lock2)); t2.start(); } } Output: Thread[Thread-1,5,main] : Trying lock Thread[Thread-0,5,main] : Trying lock Thread[Thread-0,5,main] : Acquired lock Thread[Thread-1,5,main] : Acquired lock
Comments