aspose file tools
The moose likes Threads and Synchronization and the fly likes Wait for multiple semaphores at once Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Wait for multiple semaphores at once" Watch "Wait for multiple semaphores at once" New topic
Author

Wait for multiple semaphores at once

Oliv Anirud
Greenhorn

Joined: Mar 08, 2010
Posts: 2
I have several running tasks, that release permit to semaphores as they progress. Each task has its own semaphore. These tasks are separated into two categories. Sometimes I need to wait for any permit in any task, sometimes for any task in some category, and sometimes for single task.

Is there a way to acquire a permit from any semaphore in a collection? Similar to select() in Unix I/O programming: you have collection of stream handles and wait for data in any of them.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 13408


Generally, this is a sign that the "threaded" design isn't correct.

Threads should wait for one type of work, do that work, and go back to waiting for more work. If there are more than one type of work, with more than one work queue, maybe it is a good idea to split it off -- and have different worker threads on each queue.

If it must be one type of worker threads, then maybe you can add smaller work queue threads that simple preprocesses the work orders from these separate queues and queue it into the single work queue that the worker threads are sitting on.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Alan Mehio
Ranch Hand

Joined: Apr 04, 2005
Posts: 70
Is there a way to acquire a permit from any semaphore in a collection? Similar to select() in Unix I/O programming: you have collection of stream handles and wait for data in any of them.


I am not sure if this answer the question; the semaphore are useful for implementing kind of resource pooling in your case a pool of limited stream handler so you want to put a bound or limit on of the size of stream handlers ( ELEMENTS IN THE COLLECTION) so that if this bound is being exceeded the caller thread to pull more will block until an available resource ( stream handler) is returned into the collection. In your case, you have a bounded collection and at the same time
your element (stream handler ) will block i.e will be in a wait state until an event happens


Collection of ServerSocket of size n which listen to different ports is an ideal sample of example which I will try to simulate if you would like me to continue


Hope this could help.


Regards,
Alan Mehio
London, UK
 
 
subject: Wait for multiple semaphores at once
 
developer file tools