Reputation: 10140
Using Java 6:
I have a method that uses a Thread to run a task in the background. This task accesses files, so the method should not be able to have multiple threads running.
I am trying to figure out if there is a way that I can search for active Threads at the beginning of my method. I want to know if there is an active Thread that is already running my task, so that I can handle the situation properly.
Is this possible without having an actual instance of a previous Thread handy? I would like to avoid saving instances of the Thread globally.
Upvotes: 1
Views: 190
Reputation: 2436
Use [ReentrantLock.tryLock](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html#tryLock(). If it returns false, bingo! Some other thread currently holds the lock.
Upvotes: 3
Reputation: 9941
Even if you had access to these Threads, what would you do with that knowledge? How would you tell what that Thread is currently doing?
If you have a service that can be accessed from multiple places, but you want to guarantee only a single thread will be used by this service, you can set up a work queue like this:
public class FileService
{
private final Queue workQueue = new ArrayBlockingQueue(100/*capacity*/);
public FileService()
{
new Thread()
{
public void run()
{
while(true)
{
Object request = workQueue.take(); // blocks until available
doSomeWork(request);
}
}
}.start();
}
public boolean addTask(Object param)
{
return workQueue.offer(param); // return true on success
}
}
Here, the ArrayBlockingQueue takes care of all the thread safety issues. addTask() can be called safely from any other thread; it will simply add a "job" to the workQueue. Another, internal thread will constantly read from the workQueue and perform some operation if there's work to do, otherwise it will wait quietly.
Upvotes: 2
Reputation: 131800
Just for reference: you can get all active threads in the current thread's group and its subgroups (for a standalone program, this usually can get you all threads) with java.lang.Thread.enumerate(Thread[])
. But this is not the way to solve your problem - as Brian said, use a lock.
Upvotes: 5
Reputation: 272417
You may want something a little more robust, like using a ReentrantLock to prevent concurrent access to those resources.
Upvotes: 6