I am bit new in Java Threading and concurrency. I have read about synchronized and lock blocks. They let other Threads to wait until first Thread complete its work.
I just want to know a way that if THREAD A is performing its execution, then THREAD B should not wait and skip the execution of that shared code block.
Thread B could try to acquire the lock by Lock.tryLock
. If it's not available, Thread B may skip "the execution of that shared code block" immediately after the check.
I just want to know a way that if THREAD A is performing its execution, then THREAD B should not wait and skip the execution of that shared code block.
You can use the two variants of Lock.tryLock()
one attempts to lock immediately the other waits for a given period:
final Lock lock = new ReentrantLock();
new Thread(() -> {
boolean isAcquired = lock.tryLock();
System.out.println(Thread.currentThread().getName() + " acquired lock " + isAcquired);
sleep(10000); //acquires the lock and sleeps for 10 secs
}, "Thread A").start();
sleep(1000); //main thread sleep so that Thread A locks on the lock
new Thread(() ->{
try {
//will wait for 2 secs tops to acquire the lock
boolean isAcquired = lock.tryLock(2000, TimeUnit.MILLISECONDS);
System.out.println(Thread.currentThread().getName() + " acquired lock " + isAcquired);
}catch(InterruptedException ie){
ie.printStackTrace();
}
}, "Thread B").start();
Output:
Thread A acquired lock true
Thread B acquired lock false
In the first usage the tryLock()
does not wait it attempts to acquire the lock if it can it will return true
immediately, else it will return false
.
In the second usage the tryLock(long time, TimeUnit unit)
will wait for the lock to be released for the instructed period of time
then acquire it and return true
else it will return false
or throw InterruptedException
if it is interrupted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With