Java thread wait time

wait()/wait(timeout)/sleep(timeout)?

What is the difference between wait() and wait(timeout).Anyway wait() needs to wait for a notify call but why we have wait(timeout) ? So what is the difference between sleep(timeout) and wait(timeout) ?

4 Answers 4

wait(timeout) will return if the thread is still waiting after the timeout has elapsed. This is for hang notification, for low-power polling, etc etc. Sleep(timeout) won’t wake up until the timeout has elapsed; wait(timeout) is either the notify() call or the timeout, whichever comes first.

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.

Just so it’s said. sleep(timeout) will wake up if the thread’s interrupted. But then, any of the others should too.

So if you can stop a wait my Notify and you can stop a sleep by Interrupt, then exactly what’s the difference? I want to wait x seconds, how do I decide which to choose?

wait(timeout): when the timeout expires the thread wakes up and tries to re-acquire the synchronization lock (i.e. if another thread has not notified it within the timeout period).

sleep(timeout): sleep can be used without any sycnhronization code — it just puts the thread to sleep for the specified timeout. Note that wait must be used within synchronized code.

Читайте также:  How to check if package is installed python

So, wait is used when you expect a thread to be notified by another thread (but may not, hence timeout). And, wait must be called within synchronized code.

» expect a thread to be notified by another thread » isn’t that also the purpose of Interrupt ? So what’s the difference?

The only difference between wait() and wait(timeout) is that wait() will never wake up without a notify() . wait(timeout) with a timeout > 0 allows you to potentially save yourself from locking up your application «forever» if a call to notify() never occurs.

The main difference between those two methods is that wait releases ownership of the object’s monitor while sleep doesn’t. For example, let’s say an object has two synchronized methods A() and B(). If you call wait(timeout) in A(), another thread can call B() while the other thread is waiting. But if you call sleep(timeout) in A(), the other thread can’t call B() until that sleep is over and A() is finished (since the lock on the object’s monitor is not released while sleeping).

Yes. Please refer to the Java API: Object.wait(long timeout): «The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object’s monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.» Thread.sleep(long millis): «The thread does not lose ownership of any monitors.» What you and xagyg posted is also correct, though. 🙂

This is not right. AS JLS says, Implementations are permitted, although not encouraged, to perform «spurious wake-ups»

The difference is that these methods are designed for different purposes. Sleep is used for introducing unconditional delay in thread execution, whilst wait is used for synchronization between threads, e.g.:

  1. If you want to implement countdown, delay, timer you should use sleep(t).
  2. If you have 2 (or more) threads, where 1st is a producer which spawns data randomly, whilst 2nd is consumer which consumes what 1st one provides, you should go for wait()/notify() pattern or consider modern more convenient wrappers for this threads synchronization if it’s present on your platform.
  3. If you have case 2, but you want to add a timeout to fire after certain time instead of hanging forever in wait(), you go for wait(t) instead of wait().

In fact if you never notify, wait(t) acts similarly to sleep(t) — it’s gonna return after timeout, so you could use it for case 1, but it’s much more clunky and ugly.

Источник

Pausing Execution with Sleep

Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads example in a later section.

Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we’ll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.

The SleepMessages example uses sleep to print messages at four-second intervals:

public class SleepMessages < public static void main(String args[]) throws InterruptedException < String importantInfo[] = < "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" >; for (int i = 0; i < importantInfo.length; i++) < //Pause for 4 seconds Thread.sleep(4000); //Print a message System.out.println(importantInfo[i]); >> >

Notice that main declares that it throws InterruptedException . This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn’t bother to catch InterruptedException .

Источник

How to Delay Code Execution 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.

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:

Источник

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