Java Lock Together With Status Event Using Producer Consumer Solution

You tin also solve producer consumer work yesteryear using novel lock interface too status variable instead of using synchronized keyword too hold off too notify methods.  Lock provides an alternate means to attain usual exclusion too synchronization inward Java. Advantage of Lock over synchronized keyword is good known, explicit locking is much to a greater extent than granular too powerful than synchronized keyword, for example, reach of lock tin arrive at from 1 method to approximately other but reach of synchronized keyword cannot driblet dead beyond 1 method. Condition variables are lawsuit of java.util.concurrent.locks.Condition class, which provides inter thread communication methods similar to wait, notify too notifyAll e.g. await(), signal() too signalAll(). So if 1 thread is waiting on a status yesteryear calling condition.await() too then in 1 lawsuit that status changes, minute thread tin telephone scream upwards condition.signal() or condition.signalAll() method to notify that its fourth dimension to wake-up, status has been changed. Though Lock too Condition variables are powerful they are slightly hard to purpose for start timers. If you lot are used to locking using synchronized keyword, you lot volition using Lock painful because straightaway it becomes developer's responsibleness to acquire too unloosen lock. Anyway, you lot tin follow code idiom shown hither to purpose Lock to avoid whatever concurrency issue. In this article, you lot volition larn how to purpose Lock too Condition variables inward Java yesteryear solving classic Producer Consumer problem. In social club to deeply sympathize these novel concurrency concepts, I also propose to accept a await at Java seven Concurrency Cookbook, Its 1 of the best majority inward Java concurrency amongst approximately skilful non trivial examples.



How to purpose Lock too Condition variable inward Java

You demand to live lilliputian chip careful when you lot are using Lock flat inward Java. Unlike synchronized keyword, which acquire too unloosen lock automatically, hither you lot demand to telephone scream upwards lock() method to acquire the lock too unlock() method to unloosen the lock, failing to do volition lawsuit inward deadlock, livelock or whatever other multi-threading issues.  In social club 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 yesteryear this lock      } finally {          theLock.unlock();      }

Though this idiom looks really easy, Java developer frequently makes subtle mistakes spell coding e.g. they forget to unloosen lock within lastly block. So merely recall to unloosen lock inward lastly to ensure lock is released fifty-fifty if endeavour block throws whatever exception.


How to create Lock too Condition inward Java?

Since Lock is an interface, you lot cannot create object of Lock class, but don't worry, Java provides 2 implementation of Lock interface, ReentrantLock too ReentrantReadWriteLock. You tin create object of whatever of this flat to purpose Lock inward Java. BTW, the means these 2 locks are used is unlike because ReentrantReadWriteLock contains 2 locks, read lock too write lock. In this example, you lot volition larn how to purpose ReentrantLock flat inward Java. One you lot receive got an object, you lot tin telephone scream upwards lock() method to acquire lock too unlock() method to unloosen lock. Make certain you lot follow the idiom shown higher upwards to unloosen lock within lastly clause.

In social club to hold off on explicit lock, you lot demand to create a status variable, an lawsuit of java.util.concurrent.locks.Condition class. You tin create status variable yesteryear calling lock.newCondtion() method. This flat provides method to hold off on a status too notify waiting threads, much similar Object class' hold off too notify method. Here instead of using wait() to hold off on a condition, you lot telephone scream upwards await() method. Similarly inward social club to notify waiting thread on a condition, instead of calling notify() too notifyAll(), you lot should purpose signal() too signalAll() methods. Its improve practise to purpose signalAll() to notify all threads which are waiting on approximately condition, similar to using notifyAll() instead of notify().

Just similar multiple hold off method, you lot also receive got iii version of await() method, start await() which causes electrical flow thread to hold off until signalled or interrupted,  awaitNanos(long timeout) which hold off until notification or timeout too 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 inward Java :

 You tin also solve producer consumer work yesteryear using novel lock interface too status va Java Lock too Condition Example using Producer Consumer Solution


Producer Consumer Solution using Lock too Condition

Here is our Java solution to classic Producer too Consumer problem, this fourth dimension nosotros receive got used Lock too Condition variable to solve this. If you lot recall inward past, I receive got shared tutorial to solve producer consumer work using wait() too notify() too yesteryear using novel concurrent queue flat BlockingQueue. In damage of difficultly, start 1 using hold off too notify is the most hard to acquire it correct too BlockingQueue seems to live far easier compared to that. This solution which accept payoff of Java v Lock interface too Condition variable sits correct inward betwixt these 2 solutions.

Explanation of Solution
In this programme nosotros receive got 4 classes, ProducerConsumerSolutionUsingLock is merely a wrapper flat to examine our solution. This flat creates object of ProducerConsumerImpl too producer too consumer threads, which are other 2 classes extends to Thread acts every bit producer too consumer inward 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 too Condition variable inward Java yesteryear  * solving Producer consumer problem. Locks are to a greater extent than flexible means to furnish  * usual exclusion too synchronization inward Java, a powerful choice of  * synchronized keyword.  *   * @author Javin Paul  */ public class ProducerConsumerSolutionUsingLock {      public static void main(String[] args) {          // Object on which producer too consumer thread volition operate         ProducerConsumerImpl sharedObject = new ProducerConsumerImpl();          // creating producer too consumer threads         Producer p = new Producer(sharedObject);         Consumer c = new Consumer(sharedObject);          // starting producer too 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 too 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);                  // indicate consumer thread that, buffer has chemical component subdivision 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);                  // indicate 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 select grip of 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 straightaway CONSUMER consumed 279133501 from queue  CONSUMER : Signalling that buffer may live empty now


Here you lot tin run across that CONSUMER thread has started earlier PRODUCER thread too constitute that buffer is empty, hence its waiting on status "bufferNotFull". Later when PRODUCER thread started, it added an chemical component subdivision into shared queue too indicate all threads (here merely 1 CONSUMER thread) waiting on status bufferNotFull that this status may non agree now, wake upwards too do your work. Following telephone scream upwards to signalAll() our CONSUMER thread wake upwards too checks the status again, constitute that shred queue indeed no to a greater extent than empty now, hence it has gone ahead too consumed that chemical component subdivision from queue.

Since nosotros are non using whatever infinite loop inward our program, post service this activity CONSUMER thread came out of run() method too thread is finished. PRODUCER thread is already finished, hence our programme ends here.

That's all most how to solve producer consumer work using lock too status variable inward Java. It's a skilful instance to larn how to purpose these relatively less utilized but powerful tools. Let me know if you lot receive got whatever enquiry most lock interface or status variables, happy to answer. If you lot similar this Java concurrency tutorial too desire to larn most other concurrency utilities, You tin accept a await at next tutorials every bit well.

Java Concurrency Tutorials for Beginners

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


Further Learning
Multithreading too Parallel Computing inward Java
Java Concurrency inward Practice - The Book
Applying Concurrency too Multi-threading to Common Java Patterns
Java Concurrency inward Practice Course yesteryear Heinz Kabutz



Sumber https://javarevisited.blogspot.com/

0 Response to "Java Lock Together With Status Event Using Producer Consumer Solution"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel