• 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
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

synchronize

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class SyncTest {
2 private int x;
3 private int y;
4 private d void setX( int i ) { x = i; }
5 private synchronized void setY( int i ) { y = i; }
6 public void setXY( int i ) { setX(i); setY(i); }
7 public synchronized boolean check() { return x != y; }
8 } Under which condition will check return true when called from a different class?

A. check can never return true.
B. check can return true when setXY is called by multiple threads.
C. check can return true when multiple threads call setX and setY separately.
D. check can return true only if SyncTest is changed to allow x and y to be set separately.
 
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I guess the answer is B.
 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi mehul,
can u just explain how???
 
Mehul Sanghvi
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Harish,

Assuming 2 threads are competing to execute the code there can be a possible scenario wherein
- Thread1 stops after executing setY(i)
- Thread2 stops after executing setX(i)
- Thread1 resumes to execute check() //result: false
- Thread2 resumes to execute setY(i) and then check() //result: true

Cheers.
 
Mehul Sanghvi
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Originally posted by me:

- Thread1 resumes to execute check() //result: false
- Thread2 resumes to execute setY(i) and then check() //result: true


Read that as:
- Thread1 resumes to execute check() //result: TRUE
- Thread2 resumes to execute setY(i) and then check() //result: FALSE
 
reply
    Bookmark Topic Watch Topic
  • New Topic