views:

111

answers:

4

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.

+6  A: 

You may want something a little more robust, like using a ReentrantLock to prevent concurrent access to those resources.

Brian Agnew
+5  A: 

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.

David Zaslavsky
+2  A: 

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.

Outlaw Programmer
+3  A: 

Use ReentrantLock.tryLock. If it returns false, bingo! Some other thread currently holds the lock.

Antonio