Pergunta

I've seen this approach several times, both in async and multithreaded code. A counter is used to track asynchronous behavior or thread behavior - whenever a new action is started, the counter is incremented. When it's finished, the counter is decremented.

While this is happening, another process is only able to proceed if the counter is zero. But the original process may reacquire the lock multiple times without deadlocking.

This is particularly useful as a way to handle user actions that need to be resolved before moving to another workflow.

Is there a name for this locking approach?

Foi útil?

Solução

I think you talking about ReentrantLock:

The ReentrantLock provides synchronization to methods while accessing shared resources.

The code which manipulates the shared resource is surrounded by calls to lock and unlock method.

This gives a lock to the current working thread and blocks all other threads which are trying to take a lock on the shared resource. ReentrantLock allow threads to enter into lock on a resource more than once. When the thread first enters into lock, a hold count is set to one.

Before unlocking the thread can re-enter into lock again and every time hold count is incremented by one.

For every unlock request, hold count is decremented by one and when hold count is 0, the resource is unlocked.

Reentrant Locks also offer a fairness parameter, by which the lock would abide by the order of the lock request i.e. after a thread unlocks the resource, the lock would go to the thread which has been waiting for the longest time. This fairness mode is set up by passing true to the constructor of the lock. These locks are used in the following way:

public void method() 
{ 
        reentrantlock.lock(); 
        try
        { 
            //Do some work 
        } 
        catch(Exception e) 
        { 
            e.printStackTrace(); 
        } 
        finally
        { 
            reentrantlock.unlock(); 
        }          
}

The unlock statement is always called in the finally block to ensure that the lock is released even if an exception is thrown in the method body.

Outras dicas

It sounds like you're talking about Semaphore.

Licenciado em: CC-BY-SA com atribuição
scroll top