Java Lock In Addition To Status Illustration Using Producer Consumer Solution

You tin also solve producer consumer work past times using novel lock interface too status variable instead of using synchronized keyword too hold back too notify methods.  Lock provides an alternate agency to accomplish usual exclusion too synchronization inwards 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, compass of lock tin make from i method to only about other but compass of synchronized keyword cannot croak beyond i method. Condition variables are event 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 i thread is waiting on a status past times calling condition.await() thus i time that status changes, minute thread tin telephone phone 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 role for start timers. If y'all are used to locking using synchronized keyword, y'all volition using Lock painful because at i time it becomes developer's responsibleness to acquire too liberate lock. Anyway, y'all tin follow code idiom shown hither to role Lock to avoid whatever concurrency issue. In this article, y'all volition acquire how to role Lock too Condition variables inwards Java past times solving classic Producer Consumer problem. In club to deeply sympathise these novel concurrency concepts, I also propose to accept a expect at Java seven Concurrency Cookbook, Its i of the best mass inwards Java concurrency amongst only about adept non trivial examples.



How to role Lock too Condition variable inwards Java

You demand to live piffling fighting careful when y'all are using Lock course of pedagogy inwards Java. Unlike synchronized keyword, which acquire too liberate lock automatically, hither y'all demand to telephone phone lock() method to acquire the lock too unlock() method to liberate the lock, failing to do volition upshot inwards deadlock, livelock or whatever other multi-threading issues.  In club to brand developer's life easier, Java designers has suggested next idiom to function amongst locks :

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

Though this idiom looks rattling easy, Java developer oftentimes makes subtle mistakes spell coding e.g. they forget to liberate lock within survive block. So only recall to liberate lock inwards survive to ensure lock is released fifty-fifty if attempt block throws whatever exception.


How to create Lock too Condition inwards Java?

Since Lock is an interface, y'all 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 course of pedagogy to role Lock inwards Java. BTW, the agency these 2 locks are used is unlike because ReentrantReadWriteLock contains 2 locks, read lock too write lock. In this example, y'all volition acquire how to role ReentrantLock course of pedagogy inwards Java. One y'all receive got an object, y'all tin telephone phone lock() method to acquire lock too unlock() method to liberate lock. Make certain y'all follow the idiom shown to a higher house to liberate lock within survive clause.

In club to hold back 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 course of pedagogy provides method to hold back on a status too notify waiting threads, much similar Object class' hold back too notify method. Here instead of using wait() to hold back on a condition, y'all telephone phone await() method. Similarly inwards club to notify waiting thread on a condition, instead of calling notify() too notifyAll(), y'all should role signal() too signalAll() methods. Its ameliorate practise to role signalAll() to notify all threads which are waiting on only about condition, similar to using notifyAll() instead of notify().

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

 You tin also solve producer consumer work past times 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 y'all recall inwards past, I receive got shared tutorial to solve producer consumer work using wait() too notify() too past times using novel concurrent queue course of pedagogy BlockingQueue. In price of difficultly, start i using hold back 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 five Lock interface too Condition variable sits correct inwards betwixt these 2 solutions.

Explanation of Solution
In this programme nosotros receive got 4 classes, ProducerConsumerSolutionUsingLock is only a wrapper course of pedagogy to essay our solution. This course of pedagogy creates object of ProducerConsumerImpl too producer too consumer threads, which are other 2 classes extends to Thread acts every bit producer too 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 role Lock too Condition variable inwards Java past times  * solving Producer consumer problem. Locks are to a greater extent than flexible agency to render  * usual exclusion too synchronization inwards Java, a powerful option 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);                  // betoken consumer thread that, buffer has chemical portion 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);                  // betoken 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 at i time CONSUMER consumed 279133501 from queue  CONSUMER : Signalling that buffer may live empty now


Here y'all tin run across that CONSUMER thread has started earlier PRODUCER thread too constitute that buffer is empty, thus its waiting on status "bufferNotFull". Later when PRODUCER thread started, it added an chemical portion into shared queue too betoken all threads (here only i CONSUMER thread) waiting on status bufferNotFull that this status may non concord now, wake upward too do your work. Following telephone phone to signalAll() our CONSUMER thread wake upward too checks the status again, constitute that shred queue indeed no to a greater extent than empty now, thus it has gone ahead too consumed that chemical portion from queue.

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

That's all nearly how to solve producer consumer work using lock too status variable inwards Java. It's a adept illustration to acquire how to role these relatively less utilized but powerful tools. Let me know if y'all receive got whatever interrogation nearly lock interface or status variables, happy to answer. If y'all similar this Java concurrency tutorial too desire to acquire nearly other concurrency utilities, You tin accept a expect at next tutorials every bit well.

Java Concurrency Tutorials for Beginners

  • How to role Future too FutureTask course of pedagogy inwards Java? (solution)
  • How to role CyclicBarrier course of pedagogy inwards Java? (example)
  • How to role Callable too Future course of pedagogy inwards Java? (example)
  • How to role CountDownLatch utility inwards Java? (example)
  • How to role Semaphore course of pedagogy inwards Java? (code sample)
  • What is divergence betwixt CyclicBarrier too CountDownLatch inwards Java? (answer)
  • How to role Lock interface inwards multi-threaded programming? (code sample)
  • How to role Thread puddle Executor inwards 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 five Concurrent Collection classes from Java five too Java vi (read here)
  • how to do inter thread communication using hold back too notify? (solution)
  • How to role ThreadLocal variables inwards Java? (example)


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


Belum ada Komentar untuk "Java Lock In Addition To Status Illustration Using Producer Consumer Solution"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel