• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Thread and String literal pool

 
Ranch Hand
Posts: 2066
IntelliJ IDE Clojure Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I got this question from Exam Lab Test 01.

The output :

Don't those methods be synchronized on the String Literal pool object x? Thanks in Advanced!
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes the synchronized blocks will synchronize on the String "x" from the pool. Do you have some doubts about the output?? Here run2 is called from a synchronized block, so the thread already holds the lock on the desired object when run2 is called...
 
Ranch Hand
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
line 3 is causes the method to be synchronized on the object "x"
this means that no other thread can access the synchronized code till the lock is acquired
now in that method
we call the run2() method
and this method is also synchronized on the object "x"
now when t1 or t2 is started
only one of the thread will run the synchronized code
and also the method called from the synchronized block is synchronized on the same object "x" (due to the String literal pool)
hence the method run2 can be accessed by the object of which lock the thread has acquired and it can call run2 through run method
hence
the output should contain X and then X2 for any order of the threads that are started and start executing
 
You don't like waffles? Well, do you like this tiny ad?
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic