Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in K&B Question on Thread

 
Benjamin Samuel
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
Benjamin Samuel
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Russell for your replies.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic