File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread

 
Abhi vijay
Ranch Hand
Posts: 509
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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
Posts: 757
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 55
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Vijitha Kumara
Bartender
Posts: 3908
9
Chrome Fedora Hibernate
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)?
 
Ruben Soto
Ranch Hand
Posts: 1032
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic