• Post Reply Bookmark Topic Watch Topic
  • New Topic

notifyAll()

 
mohit joshi
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If thread1 is executing the synchronized code and thread2, thread3..... are waiting for the lock, how can we implement some mechanism by which the next thread to run is thread2 and then thread3 and so on?
 
Rob Whelan
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I supposed you've noticed that there's no built-in functionality to support this. One of the primary reasons why Java lacks this support is that it's rarely needed. If you have synchronized code that takes a long time to execute (but which many threads will be accessing), you should reconsider your design to make sure you're doing it the best way.
If the code doesn't take a long time to execute, or if you won't normally have multiple threads trying to access it simultaneously, then you probably don't need to worry about keeping the access in order.

That said, if you're serious about getting more control over your threads, start with Doug Lee's concurrency utilities, at http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html.
Play around with the FIFOSemaphore class, which covers the kind of functionality you're looking for. You should also definitely evaluate QueuedExecutor, which implements a very powerful thread management model called a "task queue" (that's what I've always called it, at least) -- you define your "task" as a Runnable class, and hand it over to the queue, where the run() method will be executed in the queue's own Thread, in the order the task was received.
Optionally, you can have the task notify interested objects when it is complete. I think Sun's SwingConnection once included a decent implementation of this model, if you want another resource.

Good luck.
 
mohit joshi
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply. I will try to learn from the resources pointed out.
While reading the Certification Book RHE, I got an Idea that the while loop that checks for eligibility of a thread before letting it acquire a lock can also be used to filter which
thread should have a go at it. some thing like
synchronized{
while(condition = false | | ! currentThread().equals(treeSet.first()){
//if thread is not already in the treeset, add it here
wait();
}
//execute...
The TreeSet object can have a comparator deciding which thread should be allowed first and upon notifyAll, all threads will be tested and only the first thread of TreeSet will be allowed inside.
However, I am not sure how this may be used, or if this is appropriate way of queuing.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!