Posts

Showing posts from 2014

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.st