Java Lock In Addition To Status Example Using Producer Consumer Solution

You tin also solve producer consumer work past times using novel lock interface in addition to status variable instead of using synchronized keyword in addition to hold off in addition to notify methods.  Lock provides an alternate means to accomplish usual exclusion in addition to synchronization inwards Java. Advantage of Lock over synchronized keyword is good known, explicit locking is much to a greater extent than granular in addition to powerful than synchronized keyword, for example, orbit of lock tin attain from 1 method to unopen to other but orbit of synchronized keyword cannot move beyond 1 method. Condition variables are event of java.util.concurrent.locks.Condition class, which provides inter thread communication methods similar to wait, notify in addition to notifyAll e.g. await(), signal() in addition to signalAll(). So if 1 thread is waiting on a status past times calling condition.await() thus 1 time that status changes, minute thread tin telephone telephone condition.signal() or condition.signalAll() method to notify that its fourth dimension to wake-up, status has been changed. Though Lock in addition to Condition variables are powerful they are slightly hard to purpose for starting fourth dimension timers. If y'all are used to locking using synchronized keyword, y'all volition using Lock painful because straight off it becomes developer's responsibleness to acquire in addition to unloosen lock. Anyway, y'all tin follow code idiom shown hither to purpose Lock to avoid whatsoever concurrency issue. In this article, y'all volition acquire how to purpose Lock in addition to Condition variables inwards Java past times solving classic Producer Consumer problem. In fellowship to deeply sympathise these novel concurrency concepts, I also propose to accept a hold off at Java vii Concurrency Cookbook, Its 1 of the best mass inwards Java concurrency amongst unopen to skillful non trivial examples.



How to purpose Lock in addition to Condition variable inwards Java

You demand to live piddling fleck careful when y'all are using Lock flat inwards Java. Unlike synchronized keyword, which acquire in addition to unloosen lock automatically, hither y'all demand to telephone telephone lock() method to acquire the lock in addition to unlock() method to unloosen the lock, failing to do volition termination inwards deadlock, livelock or whatsoever other multi-threading issues.  In fellowship to brand developer's life easier, Java designers has suggested next idiom to run amongst locks :

 Lock theLock = ...;      theLock.lock();      try {          // access the resources protected past times this lock      } finally {          theLock.unlock();      }

Though this idiom looks real easy, Java developer ofttimes makes subtle mistakes piece coding e.g. they forget to unloosen lock within lastly block. So simply recollect to unloosen lock inwards lastly to ensure lock is released fifty-fifty if endeavour block throws whatsoever exception.


How to create Lock in addition to Condition inwards Java?

Since Lock is an interface, y'all cannot create object of Lock class, but don't worry, Java provides ii implementation of Lock interface, ReentrantLock in addition to ReentrantReadWriteLock. You tin create object of whatsoever of this flat to purpose Lock inwards Java. BTW, the means these ii locks are used is dissimilar because ReentrantReadWriteLock contains ii locks, read lock in addition to write lock. In this example, y'all volition acquire how to purpose ReentrantLock flat inwards Java. One y'all receive got an object, y'all tin telephone telephone lock() method to acquire lock in addition to unlock() method to unloosen lock. Make certain y'all follow the idiom shown inwards a higher house to unloosen lock within lastly clause.

In fellowship to hold off on explicit lock, y'all demand to create a status variable, an event of java.util.concurrent.locks.Condition class. You tin create status variable past times calling lock.newCondtion() method. This flat provides method to hold off on a status in addition to notify waiting threads, much similar Object class' hold off in addition to notify method. Here instead of using wait() to hold off on a condition, y'all telephone telephone await() method. Similarly inwards fellowship to notify waiting thread on a condition, instead of calling notify() in addition to notifyAll(), y'all should purpose signal() in addition to signalAll() methods. Its improve exercise to purpose signalAll() to notify all threads which are waiting on unopen to condition, similar to using notifyAll() instead of notify().

Just similar multiple hold off method, y'all also receive got iii version of await() method, starting fourth dimension await() which causes electrical flow thread to hold off until signalled or interrupted,  awaitNanos(long timeout) which hold off until notification or timeout in addition to awaitUnInterruptibly() which causes electrical flow thread to hold off until signalled. You tin non interrupt the thread if its waiting using this method. Here is sample code idiom to purpose Lock interface inwards Java :

 You tin also solve producer consumer work past times using novel lock interface in addition to status va Java Lock in addition to Condition Example using Producer Consumer Solution


Producer Consumer Solution using Lock in addition to Condition

Here is our Java solution to classic Producer in addition to Consumer problem, this fourth dimension nosotros receive got used Lock in addition to Condition variable to solve this. If y'all recollect inwards past, I receive got shared tutorial to solve producer consumer work using wait() in addition to notify() in addition to past times using novel concurrent queue flat BlockingQueue. In price of difficultly, starting fourth dimension 1 using hold off in addition to notify is the most hard to acquire it correct in addition to BlockingQueue seems to live far easier compared to that. This solution which accept payoff of Java v Lock interface in addition to Condition variable sits correct inwards betwixt these ii solutions.

Explanation of Solution
In this computer programme nosotros receive got 4 classes, ProducerConsumerSolutionUsingLock is simply a wrapper flat to essay our solution. This flat creates object of ProducerConsumerImpl in addition to producer in addition to consumer threads, which are other ii classes extends to Thread acts equally producer in addition to consumer inwards this solution.

import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;  /**  * Java Program to demonstrate how to purpose Lock in addition to Condition variable inwards Java past times  * solving Producer consumer problem. Locks are to a greater extent than flexible means to render  * usual exclusion in addition to synchronization inwards Java, a powerful choice of  * synchronized keyword.  *   * @author Javin Paul  */ public class ProducerConsumerSolutionUsingLock {      public static void main(String[] args) {          // Object on which producer in addition to consumer thread volition operate         ProducerConsumerImpl sharedObject = new ProducerConsumerImpl();          // creating producer in addition to consumer threads         Producer p = new Producer(sharedObject);         Consumer c = new Consumer(sharedObject);          // starting producer in addition to consumer threads         p.start();         c.start();     }  }  class ProducerConsumerImpl {     // producer consumer work data     private static final int CAPACITY = 10;     private final Queue queue = new LinkedList<>();     private final Random theRandom = new Random();      // lock in addition to status variables     private final Lock aLock = new ReentrantLock();     private final Condition bufferNotFull = aLock.newCondition();     private final Condition bufferNotEmpty = aLock.newCondition();      public void put() throws InterruptedException {         aLock.lock();         try {             while (queue.size() == CAPACITY) {                 System.out.println(Thread.currentThread().getName()                         + " : Buffer is full, waiting");                 bufferNotEmpty.await();             }              int number = theRandom.nextInt();             boolean isAdded = queue.offer(number);             if (isAdded) {                 System.out.printf("%s added %d into queue %n", Thread                         .currentThread().getName(), number);                  // dot consumer thread that, buffer has chemical ingredient now                 System.out.println(Thread.currentThread().getName()                         + " : Signalling that buffer is no to a greater extent than empty now");                 bufferNotFull.signalAll();             }         } finally {             aLock.unlock();         }     }      public void get() throws InterruptedException {         aLock.lock();         try {             while (queue.size() == 0) {                 System.out.println(Thread.currentThread().getName()                         + " : Buffer is empty, waiting");                 bufferNotFull.await();             }              Integer value = queue.poll();             if (value != null) {                 System.out.printf("%s consumed %d from queue %n", Thread                         .currentThread().getName(), value);                  // dot producer thread that, buffer may live empty now                 System.out.println(Thread.currentThread().getName()                         + " : Signalling that buffer may live empty now");                 bufferNotEmpty.signalAll();             }          } finally {             aLock.unlock();         }     } }  class Producer extends Thread {     ProducerConsumerImpl pc;      public Producer(ProducerConsumerImpl sharedObject) {         super("PRODUCER");         this.pc = sharedObject;     }      @Override     public void run() {         try {             pc.put();         } catch (InterruptedException e) {             e.printStackTrace();         }     } }  class Consumer extends Thread {     ProducerConsumerImpl pc;      public Consumer(ProducerConsumerImpl sharedObject) {         super("CONSUMER");         this.pc = sharedObject;     }      @Override     public void run() {         try {             pc.get();         } catch (InterruptedException e) {             // TODO Auto-generated grab block             e.printStackTrace();         }     } }  Output CONSUMER : Buffer is empty, waiting PRODUCER added 279133501 into queue  PRODUCER : Signalling that buffer is no to a greater extent than empty straight off CONSUMER consumed 279133501 from queue  CONSUMER : Signalling that buffer may live empty now


Here y'all tin come across that CONSUMER thread has started earlier PRODUCER thread in addition to industrial plant life that buffer is empty, thus its waiting on status "bufferNotFull". Later when PRODUCER thread started, it added an chemical ingredient into shared queue in addition to dot all threads (here simply 1 CONSUMER thread) waiting on status bufferNotFull that this status may non concur now, wake upwardly in addition to do your work. Following telephone telephone to signalAll() our CONSUMER thread wake upwardly in addition to checks the status again, industrial plant life that shred queue indeed no to a greater extent than empty now, thus it has gone ahead in addition to consumed that chemical ingredient from queue.

Since nosotros are non using whatsoever infinite loop inwards our program, postal service this activity CONSUMER thread came out of run() method in addition to thread is finished. PRODUCER thread is already finished, thus our computer programme ends here.

That's all well-nigh how to solve producer consumer work using lock in addition to status variable inwards Java. It's a skillful illustration to acquire how to purpose these relatively less utilized but powerful tools. Let me know if y'all receive got whatsoever inquiry well-nigh lock interface or status variables, happy to answer. If y'all similar this Java concurrency tutorial in addition to desire to acquire well-nigh other concurrency utilities, You tin accept a hold off at next tutorials equally well.

Java Concurrency Tutorials for Beginners

  • How to purpose Future in addition to FutureTask flat inwards Java? (solution)
  • How to purpose CyclicBarrier flat inwards Java? (example)
  • How to purpose Callable in addition to Future flat inwards Java? (example)
  • How to purpose CountDownLatch utility inwards Java? (example)
  • How to purpose Semaphore flat inwards Java? (code sample)
  • What is departure betwixt CyclicBarrier in addition to CountDownLatch inwards Java? (answer)
  • How to purpose Lock interface inwards multi-threaded programming? (code sample)
  • How to purpose Thread puddle Executor inwards Java? (example)
  • 10 Multi-threading in addition to Concurrency Best Practices for Java Programmers (best practices)
  • 50 Java Thread Questions for Senior in addition to Experienced Programmers (questions)
  • Top v Concurrent Collection classes from Java v in addition to Java half dozen (read here)
  • how to do inter thread communication using hold off in addition to notify? (solution)
  • How to purpose ThreadLocal variables inwards Java? (example)


Further Learning
Multithreading in addition to Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
Applying Concurrency in addition to Multi-threading to Common Java Patterns
Java Concurrency inwards Practice Course past times Heinz Kabutz


0 Response to "Java Lock In Addition To Status Example Using Producer Consumer Solution"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel