I know one difference:
If we say thread.sleep(1000), that thread will sleep for 1000 milliseconds for sure, whereas with yield() there is no such guarantee. This is useful for thread scheduling, since the thread which calls yield() may very well selected immediately again for running.
What else?
Thread.sleep()
The current thread changes state from Running to Waiting/Blocked as shown in the diagram below.
Any other thread with reference to the thread currently sleeping (say t) can interrupt it calling t.interrupt()
the call to sleep has to be encapsulated to catch the checked exception of InterruptedException
After the time period for which the thread was set to sleep it goes to the Runnable state and might not run immediately! It has to wait for the Thread Scheduler to schedule it for its time slice.
Thread.yield()
Calling it may cause the Thread Scheduler to move the current thread from Running to Runnable state and execute another same priority thread which was in Runnable state. This transition of state takes place only if there is some other thread of same priority in Runnable state. Hence the no guarantee that the thread will stop execution as the criteria of another same priority thread might not be met.
.yield() is much based on the Thread Priorities concept. (All thread are assigned priorities and when a thread of higher priority is in Runnable state it ususally preempts / stops execution of lower priority threads depending on implementation of ThreadScheduler.)
Note:
both Thread.sleep() and Thread.yield() are static functions and affect the current thread executing it.
both the functions will not let go the synchronized locks they hold.
yield merely says: now is a good time to let another thread run and is a hint to the scheduler. sleep really does that: sleep at least the given time.
yield() pauses momentarily the current thread, allowing the Thread Scheduler to execute other threads with the same priority. If there are no other threads waiting or their priority is lower, the yielded thread returns to its execution at once.
sleep() forces the current thread to halt its execution for a defined slot of time. Other waiting threads will start executing by taking advantage of this pause, that is, following the Thread Scheduler policy - whose implementation is vendor dependent.
It's not "for sure" -- it could even take an hour for your thread to get another chance to run, depending on the operating system's thread scheduling algorithm, and the presence of higher-priority threads.
The only thing yield() does is say, "Okay, I'm kind of done, so feel free to end my time slice and continue executing something else." sleep, on the other hand, says "Wake me up in X milliseconds". sleep is used for waiting, the other one for giving others a chance to run. They're not alternatives.
Related
I know the behavior of sleep method in Java.
When I call sleep method currently executing thread will stop it's execution and goes in sleep state. While it is sleeping it acquires the lock.
For example if I call sleep method as follows
Thread.sleep(50)
My Q is what happens after 50ms.
It will wake up and directly start executing or
it will go in runnable state and wait for CPU to give it a chance to execute?
In other words it will go to Runnable state and fight for CPU with other thread.
Please let me know the answer.
It will go into runnable state. There's never a guarantee a thread will be executing at a particular moment. But you can set the thread's priority to give it a better chance at getting CPU time.
Actually it depends on what operation system do you use and different operating systems has different process scheduling algorithms.
Most desktop operating systems are not real-time operating system. There is no guarantee about the precision of the sleep. When you call sleep, the thread is suspended and is not runnable until the requested duration elapses. When it's runnable again, it's up to the scheduler to run the thread again when some execution time is available.
For example, most Linux distros use CFS as default scheduling algorithm CFS uses a concept called "sleeper fairness", which considers sleeping or waiting tasks equivalent to those on the runqueue. So in your case, thread after sleeping will get a comparable share of CPU time.
It's up to the operating system scheduler. Typically, if the sleep is "sufficiently small" and the thread has enough of its timeslice left, the thread will hold onto the core and resume immediately when the sleep is finished. If the sleep is "too long" (typically around 10ms or more), then the core will be available to do other work and the thread will just be made ready-to-run when the sleep finishes. Depending on relative priorities, a new ready-to-run thread may pre-empt currently-running threads.
It will go in runnable state and wait for CPU to give it a chance to execute
I am implementing the following functionality in a load test tool to simulate heavy load on a target application:
Multiple threads are launched in concurrency to perform the same kind of operations.
Each thread will loop for n times. At the end of each loop, test results are available and are added to a list which is returned after all loops finish running.
I'm currently using Callable and Future, and putting lists of results returned by all the threads into another list after all threads finish running and give me the Future. The problem is that I can lose what is available if the execution of the program is interrupted. I want to be able to save results that are available in finishes loops while the threads are still processing remaining loops.
Is there something in Java concurrency library suitable for this purpose? Or is there a better design to the load test functionality I am building?
Thanks in advance!
You can pass your results to a BlockingQueue as they occur. This can be picked up by another thread or the one which triggered the tasks in the first place.
The java.util.concurrent.CyclicBarrier class is a synchronization mechanism that can synchronize threads progressing through some algorithm. In other words, it is a barrier that all threads must wait at, until all threads reach it, before any of the threads can continue.
Creating a CyclicBarrier
When you create a CyclicBarrier you specify how many threads are to wait at it, before releasing them. Here is how you create a CyclicBarrier:
CyclicBarrier barrier = new CyclicBarrier(2);
Waiting at a CyclicBarrier
Here is how a thread waits at a CyclicBarrier:
barrier.await();
You can also specify a timeout for the waiting thread. When the timeout has passed the thread is also released, even if not all N threads are waiting at the CyclicBarrier. Here is how you specify a timeout:
barrier.await(10, TimeUnit.SECONDS);
The waiting threads waits at the CyclicBarrier until either:
The last thread arrives (calls await() )
The thread is interrupted by another thread (another thread calls its interrupt() method)
Another waiting thread is interrupted
Another waiting thread times out while waiting at the CyclicBarrier
The CyclicBarrier.reset() method is called by some external thread.
Let's say I have a thread T and it is holding one resource R. If I call Thread.sleep() on the current thread i.e T, will it release the resource R (to let other threads use it) before going to sleep or not?
Or it will hold that resource and again when it will awake it will use the resource R and after finishing the work will it release it?
First of all, Thread.sleep() is Blocking library method. Threads may block, or pause, for several reasons: waiting for I/O completion, waiting to acquire a lock, waiting to wake up from Thread.sleep, or waiting for the result of a computation in another thread. When a thread blocks, it is usually suspended and placed in one of the blocked thread states.
So, when you call the sleep() method, Thread leaves the CPU and stops its
execution for a period of time. During this time, it's not consuming CPU time,
so the CPU can be executing other tasks.When Thread is sleeping and is
interrupted, the method throws an InterruptedException exception immediately
and doesn't wait until the sleeping time finishes.
The Java concurrency API has another method that makes a Thread object leave the CPU. It's the yield() method, which indicates to the JVM that the Thread object can leave the CPU for other tasks. The JVM does not guarantee that it will comply with this request. Normally, it's only used for debug purposes.
One of the confusion with sleep() is that how it is different from wait() method of object class.
The major difference between wait and sleep is that wait() method release the acquired monitor when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting.
From this Javamex article:
The Thread.sleep() method effectively "pauses" the current thread for a given period of time. We used it in our very first threading example to make threads display a message periodically, sleeping between messages. From the outset, it's important to be aware of the following:
it is always the current thread that is put to sleep;
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;
while sleeping, the thread still owns synchronization locks it has
acquired;
the sleep can be interrupted (sometimes useful for implementing a
cancellation function); calling sleep() with certain values can have
some subtle, global effects on the OS (see below), and vice versa,
other threads and processes running on the system can have subtle
effects on the observed sleep duration.
The thread which is going to sleep will hold the lock(not release resource) while it sleeps. A sleeping thread will not even be scheduled for the time it sleeps (or until it is interrrupted and then it wakes up)
If your resource R is java monitor, then there are only two ways to release it:
exit synchronized block
call wait on owned monitor
Javadoc says - sleep(): 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.sleep() method essentially interacts with the thread scheduler to put the current thread into a wait state for the required interval. The thread however does not lose ownership of any monitors.
In order to allow interruption, the implementation may not actually use the explicit sleep function that most OS's provide.
If the current thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of Thread class, then its interrupt status will be cleared and it will receive an InterruptedException.
I understand that Thread.currentThread().yield() is a notification to thread scheduler that it may assign cpu cycle to some other thread of same priority if any such is present.
My question is: If current thread has got lock on some object and calls yield(), will it loses that lock right away? And when thread scheduler finds out there is no such thread to assign cpu cycle, then the thread which has called yield() will again be in fight to get lock on the object which it has lost earlier??
I couldn't find it in javadoc and forums [http://www.coderanch.com/t/226223/java-programmer-SCJP/certification/does-sleep-yield-release-lock] have 50-50 answers.
I think yield() (lets say thread1) should release lock because if some thread (lets say thread2) of same priority wants to operate on same object, then it can have chance when thread scheduler eventually assign cup to thread2.
No. Thread.yield() is not like Object.wait(). It just gives up control to allow a thread switch. It will have no effect on the concurrency of your program.
There is no guarantee which thread the scheduler will run after a yield.
In Java Language specification
17.3 Sleep and Yield
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.
My comment:
In java's early days, when it did not really supported parallel executions, but only concurrent (green threads), yield() was suspending the current thread, and the jvm was picking up another thread to resume. Now-days, yield does not have much meaning as usually the tread scheduling is on OS level.
So, yield is just a hint to the JVM that current thread wants to take a rest and nothing else, it is up to the thread scheduler to decide what to do. yield does not have any synchronization semantic. If thread holds lock, it will continue to hold it.
Only wait methods of the Object class release the intrinsic lock of the current instance (the thread may have other locks acquired, they don't get released). Yield, sleep, join do not bother about locks. However, join is a little more special, you are guaranteed to see all the changes made by the thread you're waiting for to finish.
I am going through a java 6 book. A sample code snippet is given below from Threads chapter, where I need a clarification
synchronized(a){ //The thread gets the lock on 'a'
a.wait(2000);// Thread releases the lock and waits for notify only for maximum of two seconds, then goes back to runnable state
//The thread reacquires the lock
//More instructions here
}
Now my doubt is, after 2 seconds of wait time, to continue further code execution, the above code would require the lock on object 'a' and there is fair chance that the other thread (which is supposed to call notify() on a) might already be holding a lock on it.
So shouldn't the thread go to Blocking state after 2seconds wait, instead of Runnable state as mentioned above in the comments (in Line No. 2).
If another thread has the lock on the object, then yes, you are correct, it will wait. The javadocs for wait state the following behavior when the specified amount of time elapses.
"The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked"