Cm57201
Cm57201

Reputation: 3

How to make sure a single Runnable task isn't running simultaneously on two threads

For e.g. if I have a thread pool of two threads, but want each thread to be dedicated to a single type of task. i.e. task 1 can only execute on thread 1 of the pool , task 2 on thread 2 of the pool. I dont want more than two threads and I dont want two task1(s) to run simultaneously (one on each thread). Possible??

Upvotes: 0

Views: 830

Answers (3)

Ralf H
Ralf H

Reputation: 1474

Although there already is an accepted answer, you must use an AtomicBoolean instead of a volatile. Like in

AtomicBoolean task1RunningAB = new AtomicBoolean( false);

Runnable task1 = () -> {
    // compareAndSet( E, N) sets the value to N if current value matches E. 
    // Returns true if that was the case, so we must negate here
    if ( ! task1RunningAB.compareAndSet( false, true))
         return; 
    try {
        // your code
    } finally {
        task1RunningAB.set( false);
    }
};

Upvotes: 1

Vince
Vince

Reputation: 15146

If you wanna make sure a single task isn't being executed twice at the same time, use a boolean to specify whether that task is running or not:

(Java 8+)

volatile boolean task1Running = false;

Runnable task1 = () -> {
     if(task1Running)
          return; //already running, exit

     task1Running = true;
     //handle task
     task1Running = false;
};

Now when you try to execute it while it's already running, it'll exit. volatile is to ensure that when we change task1Running from the Thread managing the task, all other threads (specifically, the thread that executes the tasks) will see it right away.

Upvotes: -1

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85799

No, not possible. That's the benefit of using a thread pool: the pool will choose which thread will execute the delivered task. Note that even if you use Executors#newFixedThreadPool(2), you will have a thread pool with 2 threads, but this doesn't guarantee that each task is executed in a different thread.

If you need your tasks to be executed in different particular threads, then create your own threads instead. In case you don't want to manually create the threads, then use 2 single threaded executors. You can create them by using Executors#newSingleThreadExecutor (but this is very cumbersome).

Upvotes: 2

Related Questions