wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in K&B Question on Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in K&B Question on Thread" Watch "Doubt in K&B Question on Thread" New topic
Author

Doubt in K&B Question on Thread

Benjamin Samuel
Ranch Hand

Joined: Dec 15, 2006
Posts: 33
The following question is from K&B Thread chapter.

Assume you have a class that holds two private variables: a and b. Which of the following pairs can prevent concurrent access problems in that class? (Choose all that apply.)

A..
B..

C.public int read(){synchronized(a){return a+b;}}
public void get(int a, int b){synchronized(a){this.a=a;this.b=b;}}

D.public int read(){synchronized(a){return a+b;}}
public void set(int a, int b){synchronized(b){this.a=a;this.b=b;}}

E..
F..


Options C and D were quoted as wrong options. The reason given was that "only objects can be used to synchronize on". My doubt is, what if a and b were Integer objects! wouldn't these two options be right?
[ May 06, 2007: Message edited by: Binil Benjamin ]
Matt Russell
Ranch Hand

Joined: Aug 15, 2006
Posts: 165
Originally posted by Binil Benjamin:
<snip>
The reason given was that "only objects can be used to synchronize on". My doubt is, what if a and b were Integer objects! wouldn't these two options be right?

I'm afraid not: a and b are definitely ints in the scope of get() and set(). Even if the class fields a and b are Integer objects, they'd be hidden/shadowed (whichever is the term!) within the scope of get() and set().


Matt
Inquisition: open-source mock exam simulator for SCJP and SCWCD
Benjamin Samuel
Ranch Hand

Joined: Dec 15, 2006
Posts: 33
That was a great answer. Thanks.
But a doubt still remains. If I change the synchronization object from a to this.a, would the options be right?
[ May 06, 2007: Message edited by: Binil Benjamin ]
Matt Russell
Ranch Hand

Joined: Aug 15, 2006
Posts: 165
Originally posted by Binil Benjamin:
If I change the synchronization object from a to this.a, would the options be right?

Only option C -- assuming this.a and this.b were Integer objects, option C would prevent race conditions, but D would not. In particular, you could potentially call read() while another thread was halfway through set() and end up with an inconsistent answer.
Benjamin Samuel
Ranch Hand

Joined: Dec 15, 2006
Posts: 33
Thanks Russell for your replies.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in K&B Question on Thread