I have a fixed number n
of identical resources that need to be shared between n
or more threads. Whenever a thread needs to use a resource, it can take any available one, for which it runs an indetermininate amount of time (i.e. usage times are not uniform) and then release it.
What is a good Java data structure to manage this scenario? I can only think of one way to do it, which is by using a LinkedBlockingQueue
and the take
and put
operations as locking and releasing a resource, respectively. I'd just like a suggestion from the concurrency experts:
For those who are curious: The resources that need to be shared are identical copies of a non-reentrant FORTRAN library for computing multivariate normal CDFs and moments. Spectacular numerical library, but written in an age where thread-safe code wasn't something to be worried about. In this case we make n
copies of the library, where n = Runtime.getRuntime().availableProcessors()
.
EDIT: I don't want to create the overhead of threads to execute this library. It is already being called from multiple threads; the calling threads should just be able to lock a resource and get on with it.
UPDATE: See https://stackoverflow.com/a/19039878/586086 for the motivation and the implementation.
The pattern you're describing is a resource pool. A thread-safe queue is a reasonable way to handle the situation when the resources are fairly simple, though you might also consider a pool library such as pool4j.