Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads with no wait in Java

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.

like image 284
Bilal Avatar asked Aug 20 '19 06:08

Bilal


2 Answers

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.

like image 170
Andrew Tobilko Avatar answered Oct 05 '22 23:10

Andrew Tobilko


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.

like image 40
Fullstack Guy Avatar answered Oct 06 '22 00:10

Fullstack Guy