Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronization and Locks

 
Ida Achi
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Please help me understand why C and E are correct answers. The question is from K and B

Given:


And given these two fragments:

I. synchronized void move(long id) {
II. void move(long id) {

When either fragment I or fragment II is inserted at line 7, which are true? (Choose all that apply.)
A. Compilation fails
B. With fragment I, an exception is thrown
C. With fragment I, the output could be 4 2 4 2
D. With fragment I, the output could be 4 4 2 3
E. With fragment II, the output could be 2 4 2 4


Answer:

C and E are correct. E should be obvious. C is correct because even though move() is
synchronized, it's being invoked on two different objects.
 
Brij Garg
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think code is not complete.
Where the move method is being invoked.
 
Harpreet Singh janda
Ranch Hand
Posts: 317
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think in place of

// insert code here
 
bhanu chowdary
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brij Garg wrote:I think code is not complete.
Where the move method is being invoked.


The method is being invoked in run()
 
Rajeev Rnair
Ranch Hand
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ida Achi wrote:

Answer:

C and E are correct. E should be obvious. C is correct because even though move() is
synchronized, it's being invoked on two different objects.


The answer E is obvious because if move() method is not synchronized, the output could be 2,4,2,4 or 4,2,4,2 or even 2,2,4,4 or 4,4,2,2. It is not guaranteed.
Even if you synchronize the move() method, the two threads created are not locking each other because they are invoked on two different Chess objects. So the output again could be 4,2,4,2 or 2,4,2,4 or 2,2,4,4 or 4,4,2,2. So E is correct
D is definitely not possible

 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Ida Achi wrote :

....... move() is synchronized, it's being invoked on two different objects.


synchronization is for object, not for method! And here, no methods are being invoked on object, other than move(long g), so there is no 'work' to synchronization!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic