Search code examples
javamultithreadingblockingnonblocking

Conditional code synchronization only for specific threads


Assume that there are three groups of thread. lets say A,B, and C.

I want to create a code block in a method that blocking occurs between A and B type threads , C threads are allowed in all cases of the method invocation including the blocking portion.

In other words, if a A type of thread is in a blocked code portion, B is blocked but C is not blocked.

Do you have an idea if it is possible to do it? If so how this could be done?


Solution

  • You could have helper locking methods :

    private final ReentrantLock mLock = new ReentrantLock();
    
    void conditionalLock() {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        if (group.equals(groupA) || group.equals(groupB)) {
            mLock.lock();
        }
    }
    

    Edit changed/simplified condition as nicely suggested by erickson

    void conditionalUnlock() {
        if (mLock.isHeldByCurrentThread()) {
            mLock.unlock();
        }
    }
    

    Then, in the method of the same class :

        conditionalLock();
        try {
            // block you want to synchronize between threads of group A & B
        } finally {
            conditionalUnlock();
        }