I have a code fragment from a "Runnable" class is like that:
public void run() {
//Do some stuff
while(!someCondition){
//Do some stuff
while(anotherCondition){
try {
Thread.sleep(60000);
}catch (InterruptedException e){
logger.error(e.getMessage());
e.printStackTrace();
}
//Do some stuff
}
threadExecutor = Executors.newCachedThreadPool();
RunnableClass rc = new RunnableClass();
Thread rcThread = new Thread(rc);
rcThread.setDefaultUncaughtExceptionHandler(new SomeUncaughtExHandler());
threadExecutor.execute(rcThread);
}
//Do some stuff
}
Does calling Thread.sleep(60000); cause all of RunnableClass Threads to sleep or not?
Thread.sleep() makes the current thread sleep. This is spelled out in the Javadoc:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
Thread.sleep() only makes the calling thread sleep.
Thread.sleep() makes the current thread sleep; but it is bit confusing. This is why, now; the suggested way is to use TimeUnit sleep method. This API got added in Java SE5 version.
TimeUnit.SECONDS.sleep(5);
Javadoc :
Performs a Thread.sleep using this unit. This is a convenience method that converts time arguments into the form required by the Thread.sleep method.
Also you can use different units like SECONDS, MILLISECONDS etc to avoid any confusion on the unit of argument passed inside sleep method.
According to the manual:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds
So no, it doesn't effect all threads.
No, only the current thread sleeps. According to the documentation:
Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds
Thread.sleep(x)
causes the current thread to (sleep) suspend execution for a ‘x ‘ ms. This is an efficient means of making processor time available to the other threads of your application or other applications on your system.
Related
Consider this scenario:
I want to make several web service calls consecutively. I am only allowed to make a call every 10 seconds. I have something like this:
while(true) //we will break inside the loop eventually
{
//...
try {
Thread.sleep(10000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
//make web service call here
//...
}
As you can see, This will (hopefully) make a call approximately every 10 seconds. But my concern is that while Thread.sleep() is executing, I will get interrupted before 10 seconds and I will subsequently make a web service call that will get ignored.
This is not a multithreaded application so it runs on its own JVM. This is the only thread I am not calling interrupt() on this thread from anywhere, but I am not sure if I will run into trouble with my host machine's thread scheduler or anything.
Accuracy of timekeeping is not of great importance. I especially don't care if the 10 seconds turns into 15 seconds. But if somehow Thread.Sleep throws too soon I will be in trouble.
Is this the proper way of implementing this behaviour?
To clarify:
1- this is NOT a multi-threaded program
2- I do NOT want to do a exact times, the timing can be inaccurate as long as an unexpected exception does not get me out of the try block prematurely
I am not sure if I will run into trouble with my host machine's thread scheduler
No, the runtime will not interrupt an application thread for any reason. Only other code in your application (or code that you drag in with some framework that you choose) will interrupt threads.
Every task should specify an interruption policy: what will happen if the thread is interrupted? An application should never interrupt a thread without understanding its interrupt policy and being prepared to deal with the consequences.
So, define the interrupt policy for your thread. In your application, it is something you don't expect to happen, and if someone adds code to your application that calls interrupt() on your thread, they introduced a bug. Basically, your policy is that interruption isn't allowed. So, throwing a some unchecked exception, like IllegalStateException is a valid response.
Is this the proper way of implementing this behaviour?
No, it's not. When you are interrupted, you should signal callers that you were interrupted. This should be done by letting an InterruptedException propagate back to the caller (or a application-defined exception with similar meaning), or by restoring the interrupt status on the current thread. Suppose your interruption policy permits interruption, by terminating the loop prematurely. You should still restore the interrupt status:
while(true) {
...
try {
Thread.sleep(10000);
} catch(InterruptedException abort) {
Thread.currentThread().interrupt();
break;
}
/* Make web service call here... */
}
No, it is not guaranteed to wait for at least 10 seconds. The whole point of the sleep method throwing the checked exception InterruptedException is the possible need to end the sleep before the 10 seconds are up, by interrupting the thread.
You are wrong to focus on your program being "single threaded". In practice there is no such thing: the JVM and the JRE are permitted (and in fact do) run additional threads. The Thread.sleep() API says that the method throws InterruptedException if the sleeping thread is interrupted by another thread; it does not specify that only "user" threads are permitted to interrupt the sleeping thread.
In the below code:
class Test {
public static void main(String [] args) {
printAll(args);
}
public static void printAll(String[] lines) {
for(int i=0;i<lines.length;i++){
System.out.println(lines[i]);
Thread.currentThread().sleep(1000);
}
}
}
Will each String in the array lines output:
With exactly 1-second pause between lines?
With at least 1-second pause between lines?
Approximately 1-second pause. The thread can be woken up beforehand and you'll get an InterruptedException, or the thread can sleep for 1000ms and then not get to run immediately, so it will be 1000ms + microseconds (or more, if there are higher priority threads hogging the CPU).
You're also calling it wrong. It's Thread.sleep(1000);, as a static method it always acts on the current thread and you can't make other threads sleep with it.
So it will sleep for exactly 1 second to the best of it's knowledge. The thread.sleep method is not perfect. See this and other related questions:
https://stackoverflow.com/a/18737109/4615177
Calling Thread.sleep(1000) method, put the current executing thread in waiting state for the specified time. As per your program, it seems only a single threaded program hence,while The calling thread is in waiting state, no other thread is in running state, so after 1000 ms your thread will get chance to execute almost after 1000ms but not sure for other application where no of threads are going to execute.
Some points about Thread.sleep
1. it is always the current thread that is put to sleep
2. the thread might not sleep for the required time (or even at all);
the sleep duration will be subject to some system-specific granularity, typically 1ms;
3. while sleeping, the thread still owns synchronization locks it has acquired;
4. the sleep can be interrupted (sometimes useful for implementing a cancellation function);
5. calling sleep() with certain values can have some subtle, global effects on the OS
So at the end you can each String output will be with at least 1-second pause between lines.
And you calling it wrong. It is a static method..:)
It'll sleep for at least 1 second if not interrupted by some other thread. If some other thread interrupts it, InterruptedException will be thrown.
Ideally, it'll sleep for 1 second, once that time has elapsed, it will wait for it's turn to get into running state again.
Read the documentation. (Why did no one else say that?) The javadoc for Thread.sleep() says,
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
That's pretty vague, but that's all the guarantee you will get. The exact behavior will depend on what operating system you are running and probably on what JVM you are running.
An application that requires precise timing is called a real-time application, and there are special real-time operating systems (RTOS) that will tell you within how many microseconds of its scheduled time an event actually will occur. you can even get real-time versions of Java to run on your RTOS. http://en.wikipedia.org/wiki/Real_time_Java
I'm currently working on a Black Jack game in a school project. When the machine rolls, I want to make it wait 5 seconds each time it rolls to make it more exciting. How do I do this?
Use Thread#sleep():
Thread.sleep(5000);
The method can throw InterruptedException if any thread has interrupted the current thread. Usually you would catch the exception and handle it but if your program is single threaded, you don't need to worry about it. So you can just specify that the method calling Thread.sleep throws an InterruptedException:
public void foo() throws InterruptedException {
...
Thread.sleep();
...
}
You can use threading to sleep 5 seconds your current thread
try {
Thread.sleep(5000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
I Think this will help you :)
It can be done using the Thread Class with method sleep
Java Docs Says :
sleep(long millis);
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
Example:-
Thread.sleep(5000);
I guess you should you use a very large loop repetition in any programming language to create a delay.
Does any one know what timer the Thread.sleep(1000) method uses?
Does Thread using real time system timer or does it has it's own dedicated timer?
Thanks in advance for answers.
The Java Language Specification defers the details of the semantics of this method to the underlying system. Thus the behaviour will depend on which JVM implementation, which rt.jar you're using and presumably also which OS and hardware the application is running on.
This is all that is said about the method in the JLS (Chapter 17: Threads and Locks):
17.9 Sleep and Yield
Thread.sleep causes the currently executing thread to sleep (temporarily cease execution) for the specified duration, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors, and resumption of execution will depend on scheduling and the availability of processors on which to execute the thread.
Neither a sleep for a period of zero time nor a yield operation need have observable effects.
It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to Thread.sleep or Thread.yield, nor does the compiler have to reload values cached in registers after a call to Thread.sleep or Thread.yield.
Thread.sleep(long) is a native method. How it works is dependent on the OS and JVM implementation.
You can take a look at the native source in jvm.cpp [openjdk.java.net]:
JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
JVMWrapper("JVM_Sleep");
if (millis < 0) {
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
}
if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
}
// Save current thread state and restore it at the end of this block.
// And set new thread state to SLEEPING.
JavaThreadSleepState jtss(thread);
HS_DTRACE_PROBE1(hotspot, thread__sleep__begin, millis);
if (millis == 0) {
// When ConvertSleepToYield is on, this matches the classic VM implementation of
// JVM_Sleep. Critical for similar threading behaviour (Win32)
// It appears that in certain GUI contexts, it may be beneficial to do a short sleep
// for SOLARIS
if (ConvertSleepToYield) {
os::yield();
} else {
ThreadState old_state = thread->osthread()->get_state();
thread->osthread()->set_state(SLEEPING);
os::sleep(thread, MinSleepInterval, false);
thread->osthread()->set_state(old_state);
}
} else {
ThreadState old_state = thread->osthread()->get_state();
thread->osthread()->set_state(SLEEPING);
if (os::sleep(thread, millis, true) == OS_INTRPT) {
// An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
// us while we were sleeping. We do not overwrite those.
if (!HAS_PENDING_EXCEPTION) {
HS_DTRACE_PROBE1(hotspot, thread__sleep__end,1);
// TODO-FIXME: THROW_MSG returns which means we will not call set_state()
// to properly restore the thread state. That's likely wrong.
THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
}
}
thread->osthread()->set_state(old_state);
}
HS_DTRACE_PROBE1(hotspot, thread__sleep__end,0);
JVM_END
In the code above it is calling the operating system's sleep function.
From javadoc
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
sleep() is a static method of class Thread. How does it work when called from multiple threads. and how does it figure out the current thread of execution. ?
or may be a more generic Question would be How are static methods called from different threads ? Won't there be any concurrency problems ?
how does it figure out the current
thread of execution?
It doesn't have to. It just calls the operating system, which always sleeps the thread that called it.
The sleep method sleeps the current thread so if you are calling it from multiple threads it will sleep each of those threads. Also there's the currentThread static method which allows you to get the current executing thread.
a more generic Question would be How are static methods called from different threads ? Won't there be any concurrency problems ?
There is only a potential concurrency problem if one or more thread modifies shared state while another thread uses the same state. There is no shared state for the sleep() method.
Thread.sleep(long) is implemented natively in the java.lang.Thread class. Here's a part of its API doc:
Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds, subject to
the precision and accuracy of system timers and schedulers. The thread
does not lose ownership of any monitors.
The sleep method sleeps the thread that called it.(Based on EJP's comments) determines the currently executing thread (which called it and cause it to sleep). Java methods can determine which thread is executing it by calling Thread.currentThread()
Methods (static or non static) can be called from any number of threads simultaneously. Threre will not be any concurrency problems as long as your methods are thread safe.
You will have problems only when multiple Threads are modifying internal state of class or instance without proper synchronization.
When the virtual machine encounters a sleep(long)-statement, it will interrupt the Thread currently running. "The current Thread" on that moment is always the thread that called Thread.sleep(). Then it says:
Hey! Nothing to do in this thread (Because I have to wait). I'm going to continue an other Thread.
Changing thread is called "to yield". (Note: you can yield by yourself by calling Thread.yield();)
So, it doesn't have to figure out what the current Thread is. It is always the Thread that called sleep().
Note: You can get the current thread by calling Thread.currentThread();
A short example:
// here it is 0 millis
blahblah(); // do some stuff
// here it is 2 millis
new Thread(new MyRunnable()).start(); // We start an other thread
// here it is 2 millis
Thread.sleep(1000);
// here it is 1002 millis
MyRunnable its run() method:
// here it is 2 millis; because we got started at 2 millis
blahblah2(); // Do some other stuff
// here it is 25 millis;
Thread.sleep(300); // after calling this line the two threads are sleeping...
// here it is 325 millis;
... // some stuff
// here it is 328 millis;
return; // we are done;