• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronization without wait and notify

 
Abdul Aleem
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am not sure if this is a naive question, I would greatly appreciate
if someone could explain with a code example to solve the question below

There are two methods one synchronized and other non-synchronized e.g.



Suppose there are two Threads T1 and T2 accessing the above methods,
The question is which ever thread T1 or T2 gets to m1() then the thread
getting to m2() should wait for the thread in the synchronized method m1() to complete and then start processing m2()

Could this be achieved without creating additional locks or without using wait and notify ?

Many thanks,
Abdul
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Besides just making m2 synchronized? That's basically what you're describing.
 
Abdul Aleem
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ernest,

Yea, not synchronizing the method m2() but use synchronized block
within m2() to solve the problem.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why, is this a puzzle or test question?

But in any case, synchronized(this) { ... } around the whole body of m2 is the same as making the method synchronized.
 
Abdul Aleem
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ernest,

Yea this is actually an interview question, i am not sure what did the interviewer was expecting as the answer, I am pretty much aware that using synchronized block within m2() is same as synchronizing the method itself.

The question posted was how would you achieve the coordination of two methods by using java synchronized block only and not to use wait & notify so that any thread entering m2() will wait for thread in m1()


Thanks a lot,
Abdul
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic