Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to access a method only one?  RSS feed

 
Matt Taylor
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, I have a 5 threads running at the same time that accesses a method during runtime. What I want is, there should only be one thread that should access that method. If there is already one thread executing that method, the other threads just sleep or wait until it is finished executing...

So far what I did is:


Could someone please comment on my code?

Thanks
 
Carey Brown
Bartender
Posts: 2980
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I believe that will work.

see:
https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
 
Matt Taylor
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
^I would like to verify if I use that, will the other thread sleep/wait until the first thread exits the method?
 
Carey Brown
Bartender
Posts: 2980
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

When subsequent threads attempt to call method() while method() is busy servicing another thread, the second thread will block until the first thread is finished with method().
 
Campbell Ritchie
Marshal
Posts: 55678
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The other thread will be blocked until the method completes and the lock implicit to the synchronisation is released.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!