*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes lock question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "lock question" Watch "lock question" New topic
Author

lock question

Edgar Trania
Greenhorn

Joined: Feb 14, 2013
Posts: 7
hi everyone im new here and apparently im preparing for my exam as im posting to this section

can someone explain why if line 5 is uncomment the output will be consistent "it prints 5 consistent per line"
Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 720
sb1 is refering to new StringBuilder ("Consistent") object before the two threads start.
And sb1 is locked by one thread at a time. One thread prints 5 "Consistent" in a line. Then, the second thread prints the same thing.

Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3415
    
  12
On line 19 and 20 you create two ThreadTest3 instances and each one has it's own "inconsistent" StringBuilder instance referenced by sb1. Therefore the two threads are locking on different objects so there is no synchronization.
When you uncomment line 5, the "inconsistent" StringBuilder will no longer be referenced by sb1, because you change sb1 to reference the "consistent" StringBuilder passed to the constructor. This is the StringBuilder created on line 18. Because this is the same object passed to both instances, they are both trying to lock on the same object and so you have synchronization.


Joanne
Edgar Trania
Greenhorn

Joined: Feb 14, 2013
Posts: 7
alright thank guys your reply is really appreciated
line 18 and line 19 gets myself tricked, if line 2 change to static and ofcourse synchronized(StringBuilder.class) as well, some threads might blocked and the output prints into consistent manner am i right?
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1502
    
    5

Edgar Trania wrote:alright thank guys your reply is really appreciated
line 18 and line 19 gets myself tricked, if line 2 change to static and ofcourse synchronized(StringBuilder.class) as well, some threads might blocked and the output prints into consistent manner am i right?

Correct. Since sb1 is now static, all instances of ThreadTest3 will try to obtain lock on exactly same sb1.


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: lock question
 
Similar Threads
StringBuffer question?
Basic reference question
pass value or pass reference
Byte to String problem
java heap memory check