This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Abhi vijay wrote:Here the output is fixed, right? As we it is synchronized with a String reference s??
But If I replace synchronized(new String("s")), then Output becomes unpredictable, right?
Output is not fixed. It differs from one JVM to another. The thread t1 might go to runnable, but unless the thread scheduler pulls out the thread t1 from runnable pool to be thread of execution, the output is not fixed. It might be possible that the thread t2 might gain the access to be in running state before t1. So, my opinion. No the output is not fixed.
Can't we assume the fixed output, considering the String constant pool concept here. As the block in the run method synchronizes on a String object which will be in the constant pool (two instances of Q010, q1 & q2 shares it)?
You are both right . Both threads are synchronizing their execution on a single String object. Add this to the end of main():
System.out.println("q1.s and q2.s are " + (q1.s == q2.s ? "the same object" : "different"));
So that means there are 2 possible outputs, depending on which thread starts running first.
All code in my posts, unless a source is explicitly mentioned, is my own.