• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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: 9692
42
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
 
Won't you be my neighbor? - Fred Rogers. tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic