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?
Treimin Clark
Ranch Hand
Joined: Nov 12, 2008
Posts: 757
posted
0
String s="hello"; creates a String instance in the String pool, which can be reused.
But new String("hello") always create new instances.
Vinayak Bhat
Ranch Hand
Joined: May 15, 2008
Posts: 55
posted
0
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.
Himalay Majumdar
Ranch Hand
Joined: Sep 28, 2008
Posts: 324
posted
0
Treimin Clark wrote:String s="hello"; creates a String instance in the String pool, which can be reused.
But new String("hello") always create new instances.
String constant pool is not a collection of String objects, it's a collection of references to String objects. For further reference visit String Constant Pool