Java blocks other critical sections

I have a static method that multiple threads will access, as shown below. What I would like to do is allow any number of threads to execute block 1, while no thread is currently executing block 2, and vice versa. In principle, executing one block puts a lock on another block, but not on itself. ReentrantReadWriteLock does a little what I want, because I can place a read lock around block 1 and a write lock around block 2, but it is still limited in that I cannot simultaneously execute multiple threads executing block 2. Any suggestions ?

public class SomeClass
{
    ...
    public static void someMethod()
    {
        ...
        if(someCondition == true)            //Begin block 1
        {
           doSomething();
        }                                    //End block 1

        else if(someCondition == false)      //Begin block 2
        {
           doSomething();
        }                                    //End block 2
        ...
    }
    ...
}
+4
source share
1 answer

, : : enterA(), leaveA(), enterB(), leaveB(); , var aCount bCount.

enterA:
    lock mutex
    wait on condition var until bCount is zero
    increment aCount
    unlock mutex

leaveA:
    lock mutex
    decrement aCount
    notify condition var if aCount==0
    unlock mutex

enterB() leaveB() , inc/dec bCount aCount == 0.

+1

Source: https://habr.com/ru/post/1534328/


All Articles