Search code examples
javamultithreadingconcurrencyparallel-processinglocking

What is the actual usecase of trylock in java


What is the actual usecase of trylock in java. If I check trylock in if block and write an else block, I will end up loosing actual business logic which is there in if block and thread will never hit the if block again. I am wondering what could be actual business usecase for this.

I am trying to use reentrantLock.tryLock()


Solution

  • The actual use case of tryLock() in Java is to acquire the lock only if it is available at the time of invocation. This is useful in scenarios where you don't want the thread to wait forever for the lock. If the lock is not available, the thread can perform some other tasks instead of waiting. The tryLock() method returns a boolean value indicating whether the lock was acquired or not, which can be used in an if-else block to decide what to do next.

    In your case, if the business logic in the if block is important and must be executed, you should not use tryLock(). Instead, use lock() which makes the thread wait until the lock is available.

    Example use case: you have a time consuming process which is executed in worker thread, which is executed under a lock. You need to finish your application, and to gracefully finish worker process you will have to wait for its lock release. To do it you will set a flag informing the process that it should finish as soon as possible, and also will periodically call tryLock on its lock to check if it is actually finished (tryLock would return true then). In your if(!lock.tryLock()) { block you can log the reason for the delay, you can add short sleep to not hog the CPU. As Mark Rotteveel suggested, using tryLock(long time, TimeUnit unit) would be best here. If the closing time is too long you can take actions to finish the worker process less gracefully.