Moment For Technology

King concurrent course - Platinum 6: The blue -Condition how to wait and notice to play a new pattern

Posted on Dec. 2, 2022, 7:38 p.m. by Janet Robertson
Category: The back-end Tag: The back-end java

Welcome to The 19th article in this series on Concurrency.

In the last article, we introduced blocking queues. If you read the source code, you'll notice the condition variable and its use when reading and writing to queues. So, here's the ins and outs of Condition and its use.

We've mentioned the keyword synchronized several times in this series of articles, and you're pretty sure you're familiar with its use. Synchronized = "synchronized" = "synchronized" = "synchronized" = "synchronized" = "synchronized" = "synchronized" = "synchronized"

public class CountingSemaphore {
  private int signals = 0;
  public synchronized void take(a) {
    this.signals++;
    this.notify();  // Send a notification
  }
  public synchronized void release(a) throws InterruptedException {
    while (this.signals == 0)
      this.wait(); // Release the lock and enter the waitThis.signals--; }}Copy the code

Synchronized is Java's native synchronization tool, and wait and notify are its native partners. However, in the Platinum series, we have started the Lock interface and some of its implementations, such as ReentrantLock and so on. These lock tools encapsulated by JUC are much more versatile and easier to use than synchronized. As a result, the Condition emerges as The Times require.

For example, in the blocking queue above, Condition already appears:

public class LinkedBlockingQueue  E  extends AbstractQueue  E 
    implements BlockingQueue  E,java.io.Serializable {... Omit some source code/ / define the Condition
        // Note that there are two Condition objects defined to wake up different threads
        private final Condition notEmpty = takeLock.newCondition();
        private final Condition notFull = putLock.newCondition();

        public E take(a) throws InterruptedException {
            E x;
            int c = -1;
            final AtomicInteger count = this.count;
            final ReentrantLock takeLock = this.takeLock;
            takeLock.lockInterruptibly();
            try {
                while (count.get() == 0) {
                    // Enter the wait
                    notEmpty.await();
                }
                x = dequeue();
                c = count.getAndDecrement();
                if (c  1)
                    notEmpty.signal();
            } finally {
                takeLock.unlock();
            }
            if (c == capacity)
                signalNotFull();
            return x;
        }

        private void signalNotEmpty(a) {
            final ReentrantLock takeLock = this.takeLock;
            takeLock.lock();
            try {
                // Send the wake up signal
                notEmpty.signal();
            } finally{ takeLock.unlock(); }}... Omit source code several}Copy the code

Condition is an enhanced version of wait, notify, and notifyAll. It has the capabilities of wait and notify, and it also has the capabilities of wait and notify.

Condition in JUC comes in the form of an interface and defines some core methods:

  • await(): Causes the current thread to wait until it receives a signal or is interrupted;
  • await(long time, TimeUnit unit): Causes the current thread to wait until a signal is received or it is interrupted, or the specified wait timeout period is reached;
  • awaitNanos(long nanosTimeout): make the current thread wait until it receives a signal, or is interrupted, or reaches the specified wait timeout, but the unit of time is different from the previous method;
  • AwaitUninterruptibly ():Puts the current thread into wait until a signal is received. Note that this method is interrupt insensitive;
  • awaitUntil(Date deadline):Causes the current thread to wait until either a signal is received or it is interrupted, or the cutoff time is reached;
  • signal(): Wakes up a thread at random
  • signalAll(): Wakes up all waiting threads.

As you can see from the Condition's core methods, there are significant enhancements over native notification and wait methods, such as awaitUninterruptibly() and awaitUntil(). In addition, it is interesting that Condition can wake up a given thread.

As an interface, we don't need to implement Condition manually, JUC already provides an implementation, and you can use it directly in ReentrantLock. The relationships between related classes and interfaces are as follows:

summary

That's all about Condition. Condition is not complicated. It is the counterpart of JUC Lock and is understood in conjunction with the native wait and notify. Conditions and their differences are detailed in the following table:

Compare the item Object's Monitor methods Condition
precondition Gets the lock of the object Call Lock to get the Lock, and call lock.newcondition () to get the Condition object
Call way Call directly, such as object.wait() Call directly, such as condition.await()
Number of waiting queues a multiple
The current thread releases the lock and enters the wait state ✔ ︎ ✔ ︎
The current thread releases the lock and enters the wait state without responding to interrupts while waiting ✔ ︎
The current thread releases the lock and enters a timeout wait ✔ ︎ ✔ ︎
The current thread releases the lock and enters wait until some point in the future ✔ ︎
Wakes up a thread in the waiting queue ✔ ︎ ✔ ︎
Wake up all threads in the waiting queue ✔ ︎ ✔ ︎

Understand the differences in the table, not by rote, but by key points based on the methods defined in the Condition interface.

At the end of the text, congratulations on your another star ✨

The teacher's trial

  • Write code to use Condition to wake up the specified thread.

Further reading and references

About the author

Pay attention to [technology 8:30], get the article updates in time. Pass on quality technical articles, record the coming-of-age stories of ordinary people, and occasionally talk about life and ideals. 8:30 in the morning push author quality original, 20:30 in the evening push industry depth good article.

If this article is helpful to you, welcome to like, follow, supervise, we together from bronze to king.

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.