Wait in java code

wait and notify() Methods in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

Читайте также:  Html css круглый прогресс бар

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this tutorial, we’ll look at one of the most fundamental mechanisms in Java — thread synchronization.

We’ll first discuss some essential concurrency-related terms and methodologies.

Further reading:

Guide to the Synchronized Keyword in Java

How to Start a Thread in Java

And we’ll develop a simple application where we’ll deal with concurrency issues, with the goal of better understanding wait() and notify().

2. Thread Synchronization in Java

In a multithreaded environment, multiple threads might try to modify the same resource. Not managing threads properly will of course lead to consistency issues.

2.1. Guarded Blocks in Java

One tool we can use to coordinate actions of multiple threads in Java is guarded blocks. Such blocks keep a check for a particular condition before resuming the execution.

With that in mind, we’ll make use of the following:

We can better understand this from the following diagram depicting the life cycle of a Thread:

Java - Wait and Notify

Please note that there are many ways of controlling this life cycle. However, in this article, we’re going to focus only on wait() and notify().

3. The wait() Method

Simply put, calling wait() forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object.

For this, the current thread must own the object’s monitor. According to Javadocs, this can happen in the following ways:

  • when we’ve executed synchronized instance method for the given object
  • when we’ve executed the body of a synchronized block on the given object
  • by executing synchronized static methods for objects of type Class

Note that only one active thread can own an object’s monitor at a time.

This wait() method comes with three overloaded signatures. Let’s have a look at these.

3.1. wait()

The wait() method causes the current thread to wait indefinitely until another thread either invokes notify() for this object or notifyAll().

3.2. wait(long timeout)

Using this method, we can specify a timeout after which a thread will be woken up automatically. A thread can be woken up before reaching the timeout using notify() or notifyAll().

Note that calling wait(0) is the same as calling wait().

3.3. wait(long timeout, int nanos)

This is yet another signature providing the same functionality. The only difference here is that we can provide higher precision.

The total timeout period (in nanoseconds) is calculated as 1_000_000*timeout + nanos.

4. notify() and notifyAll()

We use the notify() method for waking up threads that are waiting for access to this object’s monitor.

There are two ways of notifying waiting threads.

4.1. notify()

For all threads waiting on this object’s monitor (by using any one of the wait() methods), the method notify() notifies any one of them to wake up arbitrarily. The choice of exactly which thread to wake is nondeterministic and depends upon the implementation.

Читайте также:  Php указать относительный путь

Since notify() wakes up a single random thread, we can use it to implement mutually exclusive locking where threads are doing similar tasks. But in most cases, it would be more viable to implement notifyAll().

4.2. notifyAll()

This method simply wakes all threads that are waiting on this object’s monitor.

The awakened threads will compete in the usual manner, like any other thread that is trying to synchronize on this object.

But before we allow their execution to continue, always define a quick check for the condition required to proceed with the thread. This is because there may be some situations where the thread got woken up without receiving a notification (this scenario is discussed later in an example).

5. Sender-Receiver Synchronization Problem

Now that we understand the basics, let’s go through a simple SenderReceiver application that will make use of the wait() and notify() methods to set up synchronization between them:

  • The Sender is supposed to send a data packet to the Receiver.
  • The Receiver cannot process the data packet until the Sender finishes sending it.
  • Similarly, the Sender shouldn’t attempt to send another packet unless the Receiver has already processed the previous packet.

Let’s first create a Data class that consists of the data packet that will be sent from Sender to Receiver. We’ll use wait() and notifyAll() to set up synchronization between them:

public class Data < private String packet; // True if receiver should wait // False if sender should wait private boolean transfer = true; public synchronized String receive() < while (transfer) < try < wait(); >catch (InterruptedException e) < Thread.currentThread().interrupt(); System.err.println("Thread Interrupted"); >> transfer = true; String returnPacket = packet; notifyAll(); return returnPacket; > public synchronized void send(String packet) < while (!transfer) < try < wait(); >catch (InterruptedException e) < Thread.currentThread().interrupt(); System.err.println("Thread Interrupted"); >> transfer = false; this.packet = packet; notifyAll(); > >

Let’s break down what’s going on here:

  • The packet variable denotes the data that is being transferred over the network.
  • We have a boolean variable transfer, which the Sender and Receiver will use for synchronization:
    • If this variable is true, the Receiver should wait for Sender to send the message.
    • If it’s false, Sender should wait for Receiver to receive the message.
    • If transfer is false, we’ll wait by calling wait() on this thread.
    • But when it is true, we toggle the status, set our message, and call notifyAll() to wake up other threads to specify that a significant event has occurred and they can check if they can continue execution.
    • If the transfer was set to false by Sender, only then will it proceed, otherwise we’ll call wait() on this thread.
    • When the condition is met, we toggle the status, notify all waiting threads to wake up, and return the data packet that was received.

    5.1. Why Enclose wait() in a while Loop?

    Since notify() and notifyAll() randomly wake up threads that are waiting on this object’s monitor, it’s not always important that the condition is met. Sometimes the thread is woken up, but the condition isn’t actually satisfied yet.

    We can also define a check to save us from spurious wakeups — where a thread can wake up from waiting without ever having received a notification.

    5.2. Why Do We Need to Synchronize send() and receive() Methods?

    We placed these methods inside synchronized methods to provide intrinsic locks. If a thread calling wait() method does not own the inherent lock, an error will be thrown.

    We’ll now create Sender and Receiver and implement the Runnable interface on both so that their instances can be executed by a thread.

    First, we’ll see how Sender will work:

    public class Sender implements Runnable < private Data data; // standard constructors public void run() < String packets[] = < "First packet", "Second packet", "Third packet", "Fourth packet", "End" >; for (String packet : packets) < data.send(packet); // Thread.sleep() to mimic heavy server-side processing try < Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); >catch (InterruptedException e) < Thread.currentThread().interrupt(); System.err.println("Thread Interrupted"); >> > >

    Let’s take a closer look at this Sender:

    • We’re creating some random data packets that will be sent across the network in packets[] array.
    • For each packet, we’re merely calling send().
    • Then we’re calling Thread.sleep() with random interval to mimic heavy server-side processing.

    Finally, let’s implement our Receiver:

    public class Receiver implements Runnable < private Data load; // standard constructors public void run() < for(String receivedMessage = load.receive(); !"End".equals(receivedMessage); receivedMessage = load.receive()) < System.out.println(receivedMessage); //Thread.sleep() to mimic heavy server-side processing try < Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); >catch (InterruptedException e) < Thread.currentThread().interrupt(); System.err.println("Thread Interrupted"); >> > >

    Here, we’re simply calling load.receive() in the loop until we get the last “End” data packet.

    Let’s now see this application in action:

    public static void main(String[] args)

    We’ll receive the following output:

    First packet Second packet Third packet Fourth packet 

    And here we are. We’ve received all data packets in the right, sequential order and successfully established the correct communication between our sender and receiver.

    6. Conclusion

    In this article, we discussed some core synchronization concepts in Java. More specifically, we focused on how we can use wait() and notify() to solve interesting synchronization problems. Finally, we went through a code sample where we applied these concepts in practice.

    Before we close, it’s worth mentioning that all these low-level APIs, such as wait(), notify() and notifyAll(), are traditional methods that work well, but higher-level mechanisms are often simpler and better — such as Java’s native Lock and Condition interfaces (available in java.util.concurrent.locks package).

    For more information on the java.util.concurrent package, visit our overview of the java.util.concurrent article. And Lock and Condition are covered in the guide to java.util.concurrent.Locks.

    As always, the complete code snippets used in this article are available over on GitHub.

    announcement - icon

    Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

    The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

    Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

    Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

    Источник

Оцените статью