Allow only two threads for a function

I have an unusual problem. I have a function, an operation in this function can be performed by two threads at a time.

static int iCount = 1; public synchronized void myFunct(){ while(iCount >= 3) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } iCount++; //Do Stuffs //After operation decrement count iCount --; notifyAll(); } 

What I'm trying to do, I want to allow only two threads to perform some operation, and other threads must wait.

But here, the first two threads increment the counter and perform the operation and other threads for the wait state, but do not receive a notification.

I think I'm missing something.

+4
source share
7 answers

It looks like you want to use Semaphore , you always call acquire() before performing the operation, and then release() in the finally block.

 private static final Semphore semaphore = new Semaphore(2); public static void myFunct() throws InterruptedException { semaphore.aquire(); try { // do stuff } finally { semaphore.release(); } } 
+11
source

Your function is synchronized , so there can only be one thread in it.

I'm not sure I understand your question ... But if you want two threads to be able to go somewhere right away, take a look at Semaphore .

+2
source

Is this a singleton class? If not, then this is a problem, because many parallel instances can change the value of icounter and, in addition, they will block it forever, because no thread can notify about their instance.

In any case, you must move the synchronization inside the function and block the iCount, not the instance, also make it unstable.

 public void myFunct(){ synchronized(iCount) { while(iCount >= 3) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } iCount++; } //Do Stuffs //After operation decrement count synchronized(iCount) { iCount--; } notifyAll(); 
+2
source

You need java.util.concurrent.Semaphore , initialized with two permissions.

As for your current code, threads can cache variable values. Try adding the volatile keyword.

+1
source

Why aren't you using Semaphore ?

+1
source

An alternative would be to use a ThreadPoolExecutor with a maximum of two threads.

+1
source

There are a lot of problems with this code. Among them:

  • You have no real control over the number of threads myFunct runs on, since the method is synchronized at the instance level, and the counter is static. Thus, N different threads working in N different instances can simultaneously run the same method.

  • Multiple thread counter manipulation is not thread safe. Try syncing it or using AtomicInteger.

Regarding thread limits, consider using the Semaphore class.

+1
source

All Articles