about synchronization with two threads [duplicate] - java

This question already has answers here:
Threads access on Synchronized Block/Code Java
(2 answers)
Closed 5 years ago.
Say one singleton instance accessed by two threads. Two threads are accessing the same function called doTask().
public class MySingleton {
Object lock = new Object();
// I omit the constructor here.
public void doTask() {
//first non-synchronized code
synchronize(lock) {
//some heavy task
}
//final non-synchronized code
}
}
If thread B is doing the heavy task, when thread A access doTask(), I know Thread A will run the //first non-synchronized code, then thread A noticed the lock is acquired by Thread B, so it can't run synchronized //some heavy task. But would thread A skip the synchronized heavy task continue run //final non-synchronized code or will thread A wait for the lock without even executing the //final non-synchronized code?
(I know I can try it out, but currently I don't have a proper development environment...)

The synchronized block in java forces threads to wait until they can acquire the object's lock.
It will wait until B is done, and then snag the lock for lock, and run the code inside the block, and continue out the other end.
It is important to note that when B finishes executing the contents of some heavy task it will release the lock on lock and run the final non-synchronized code at the "same time" that A runs the synchronized block.

When one thread acquires the monitor of synchronous object, then the remaining threads will also try to acquire it and this process is termed as POLLING. Because all the remaining threads try to acquire the monitor of that object by repeatedly checking the monitor lock status. The moment when the lock is released it can be acquired by any thread. It's actually decided by the scheduler.

Thread A will always wait indefinitely until Thread B releases the lock.
In the extreme case, if the lock is never released, Thread A will be stuck forever.
Sometimes this is good enough but often you will need better control over things, this is when classes like ReentrantLock come handy.
This can do everything synchronized offers, but can also do things like checking whether the lock is owned by the current thread already, attempting to acquire the lock without waiting (failing instantly if the lock is already taken by another thread), or limit its waiting to a certain amount of time.
Please also note that while these solutions can be used to control mutual exclusion, this isn't their only function, they also play an important role in visibility.

Related

ReentrantLock Condition how does signallAll() work?

I am trying to understand How does signalAll() not break the critical section for example
//Some Class Here is Trying to use an resource which is to to initialized in an seperate thread
ReentrantLock lock=new ReentrantLock();
Condition wait=lock.newCondition();
Resource res=new Resource(lock); //An Important Resource Which Should Be Accessed Only By One Thread At A Time
void doStuff()
{
lock.lock();
try
{
if(!res.initialized.get()) //Check If Resource Was Previously Not Initialized
{
res.init();//Spawns An Seperate Thread For Initialization
wait.await();//If Resource Is Not Initialized Make Whatever Thread Which Reached This Point Wait
}
res.use(); //Here Is What I Don't Understand If Let's Say 5 threads were parked in the previous statement then when signalAll() is called won't all 5 threads wake up simultaneously and resume execution at this point and use this resource at the same time and break this resource? But it dosen't turn out like that why?
}
}
finally{lock.unlock();}
}
private static final class Resource extends Thread
{
private final ReentrantLock lock;
private final Condition init;
private final AtomicBoolean
started=new AtomicBoolean(false),
initialized=new AtomicBoolean(false);
private Resource(ReentrantLock lock)
{
this.lock=lock;
this.init=lock.newCondition();
}
private void init()
{
if(!initialized.get())
{
if(!started.get())
{
start();
started.set(true);
}
while(!initialized.get()){init.awaitUninterruptibly();}//In case of spurrous wakeups check repeatedlly
}
}
private void use(){}//Important Stuff
private int get(){return 5;}
#Override
public void run()
{
lock.lock();
try
{
TimeUnit.SECONDS.sleep(5);
initialized.set(true);
init.signalAll(); //This should in the above example wake up all 5 threads simultaneously and break the critical section but that does not happen how?
}
catch(InterruptedException ex){}
finally{lock.unlock();}
}
}
With just signal() only one thread wakes up and resumes execution at the critical section so nothing breaks but with signalAll() multiple threads resumes execution at the point it was parked[i.e inside the critical section] so how does nothing break? and when/where should we use each i.e best practises
The short answer:
await() does not only suspend the current thread, it also releases the lock. signalAll() wakes up all suspended threads but each thread has to re-acquire the lock before the await() call can return. With it, even after calling notifyAll() the critical section can only be entered by a thread after the thread that acquired the lock before relinquishes the lock.
The long answer:
For better understanding - let's pretend that neither await(), singal() nor signalAll() would exist in Java. How would you wait for the asynchronous initialization of your resource? Your code would probably look something like this:
void doStuff(Resource resource) throws InterruptedException {
lock.lock();
try {
while (!resource.isInitialized()) {
resource.startAsyncInit();
lock.unlock();
Thread.sleep(100);
lock.lock();
}
doSomethingWith(resource);
} finally {
lock.unlock();
}
}
But this would have the following drawback:
Each thread that waits for initialization is suspended and woken up again and again.
Each single thread acquires the lock and releases the lock again and again.
The more frequent you do this and the more threads are waiting the more expensive
does it get. This busy waiting consumes CPU. Without an explicit sleep the code would easily
lead to 100% CPU usage.
await() allows you to replace the busy waiting with a signal-based mechanism.
All waiting threads are suspended and do not consume any CPU while they are waiting.
Only sporadically occuring spurious wake-ups (at least on some systems) may consume some CPU.
When to use singal(), signallAll() in general:
Waking up a thread and suspending a thread is not for free and gets more expensive with
the number of threads. If you have a resource that has to be initialized
before it can be used concurrently by all threads it makes sense to wake up all threads at once by calling signalAll().
But think of a consumer/producer pattern with multiple consumer threads and multiple producer threads where a single producer thread provides only one work item that is processed by one consumer thread. In this case it would make much more sense that a producer thread wakes up only one consumer thread instead of all. Otherwise all awakened threads would first compete for the single work item, one would win and all others would have to be sent back to sleep again. This would have to be repeated every time when a single work item is produced. When a lot of work items are produced in short time
you would finally loose all the advantage of the singalling. The majority of threads would be suspended and woken up again and again, they would compete for one single item again and again and you would finally end up with nearly the same overhead as the example above with busy waiting but without an explicit sleep ;-)
signal() vs signalAll() in your example:
When the first thread gets the hold of the lock it calls the init() method, starts the thread for initialization and then releases the lock when it calls awaitUninterruptibly(). The initialization thread in the meanwhile tries to acquire the lock but it will not get it until awaitUninterruptibly() is called.
Locks are by default unfair. This means that it is not guaranteed that the longest-waiting thread will get the lock first. When awaitUninterruptibly() is actually called and the lock is released other theads may have already tried to acquire the lock in the meanwhile by calling the lock() method. Even when your initialization thread tried to acquire the lock first, it is not guaranteed that it will get the lock before any other thread. Every other thread that will get the lock before your initialization thread will be able to call the await() method. If you then only call singal() in your initialization thread all threads that were able to get to the await() call would never be woken up and sleep forever. To avoid this, it is essential to use singalAll() in your example. Another possibility would be to use a "fair" lock (see the JavaDoc of the ReentrantLock). With a "fair" lock it shouldn't make any difference whether you call singal() or signalAll(). But since "fair" locks have quite an overhead I would suggest to keep the unfair lock and use singalAll().
Whether you run into a situation where some threads sleep forever depends on the right timing. So you propably may run this code on one host hundreds of times without any problem but run into this situation frequently on other hosts. Even worse, in environments with spurious wake-ups you would run into this only from time to time ;-)

Confusion with wait and Sleep method of thread

sleep() maintains the lock but wait() does not,
my thinking on wait is that it releases the lock as to give other threads a chance to acquire the monitor on that thread while he is waiting.
but having doubt with sleep() why thread maintains the lock while sleeping as it always comes to the runnable state after sleeping
why thread maintains the lock while sleeping as it always comes to the runnable state after sleeping
Consider the below scenario:-
private Object objLock = new Object();
public void myMethod() {
....
synchronized(objLock) {
Thread.sleep(1000); // make the current running thread sleep for 1 second only.
... // Code here which needs to be executed immediately after 1 second sleep time
}
....
}
If at all JVM relesed lock when sleep was called in the above code then when it comes back to runnable state (resumption of execution will depend on scheduling and the availability of processors on which to execute the thread as per JLS Sleep ) your program may not resume at all if another thread by chance took a lock which would make the program behaviour inconsistent. This could be one of the reasons why it doesnot release any locks.
Thread.sleep doesn't have anything to do with locking.
Object.wait needs to be called when holding a lock because the test for the condition to stop waiting needs to be done while holding the lock, in order to have a consistent view of the condition. But usually a thread isn't holding a lock while sleeping.
Sleeping while holding a lock would seem like really bad behavior. But if you need multiple locks, where you acquire one, and have to back off before retrying getting the other, then sleeping while holding a lock might make sense. If calling sleep released locks, this kind of back-off tactic would not work.
Having Thread.sleep be oblivious to locks makes the API simpler and gives the programmer more options (by not totally ruling out its use by a thread that needs to hold onto a lock).
Q: What does Thread.sleep(n) do?
A: NOTHING. Absolutely nothing at all.
Q: How long does it take?
A: At least n milliseconds if the thread is not interrupted.
You don't need to know much else about Thread.sleep().

How does two threads not able to execute method at the same time. Internally what happens in the code.

I have a method which is synchronized defined in some class.
We know that if we create a method as synchronized, then only one thread is able to execute the task at a time.
What is happening inside this method ?
How does other thread not able to execute the same task to run same method.
As per my knowledge, join is applied on that particular thread. But how does the second thread in the pipeline knows about the task has been done by first thread.
Tell me if i am right.
In the Java language, each Object has what is called a Monitor, which basically is a lock.
This lock is what powers Object methods such as wait / signal / signalAll that are available on every objects.
When using the synchronized keyword, what happens behind the scenes is that the compiler writes code that acquires the monitor (the lock) and releases it when invocation is complete.
If the method is static, the Monitor that is accessed is that of the Class object.
You can read more about this keyword here :
http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
One thread (first) acquires a lock on the object, and another thread waits for getting lock of that object.
Once task is done, first thread sends notification to waiting threads using notify() and notifyAll() methods.
We know that if we create a method as synchronized, then only one thread is able to execute the task at a time.
Not True! Two or more threads can enter the same synchronized block at the same time. And, that's not just in theory: It often happens in well-designed programs.
Here's what two or more threads can not do: Two or more threads can not synchronize on the same object at the same time. If you want to insure that only one thread at a time can enter a particular method (but why?†) then you need to write the method so that all calls to it will synchronize on the same object. That's easy to do if it's a static method because this:
class Foobar {
synchronized MyType baz() { ... }
}
means the same as this:
class Foobar {
MyType baz () {
synchronized (Foobar.class) { ... }
}
}
All calls to a static synchronized method synchronize on the class object that owns the method.
[what prevents two threads from synchronizing on the same object at the same time]?
The operating system. Any JVM that you would want to use for real work uses native threads to implement Java threads. A native thread is a thread that is created and managed by calls to the operating system. In particular, it's a part of the operating system known as the scheduler. I am not going to go into the details of how an operating system scheduler works---there's whole books written about that topic---but its job is to decide which threads get to run, when, and on what processor.
A typical scheduler uses queues to keep track of all of the threads that are not actually running. One special queue, the run queue, holds threads that are ready to run, but waiting for a CPU to run on. A thread on the run queue is called runnable. A thread on any other queue is blocked (i.e., not allowed to run) until something happens that causes the scheduler to put it back on the run queue.
The operating system object corresponding to a Java monitor (See #TheLostMind's answer) often is called a mutex or a lock. For each mutex, there is a queue of threads that are blocked, waiting to enter it. A native thread enters a mutex by calling the operating system. That gives the operating system the opportunity to pause the thread and add it to the mutex's queue if some other thread is already in the mutex. When a thread leaves a mutex, that's a system call too; and it gives the scheduler the opportunity to pick one thread off the mutex's queue, and put it back on the run queue.
Like I said, the details of how the scheduler does those things go way too deep to talk about here. Google is your friend.
† Don't worry about which threads can enter which method at the same time. Worry instead about which threads touch which data. The purpose of synchronization is to allow one thread to temporarily put your data into a state that you don't want other threads to see.
What is happening inside this method ?
When you say a (instance level) method is synchronized, A thread must first get a lock on the Object (i.e, first hold the monitor of that object) to access it. As long as one thread holds the lock / monitor, other threads cannot access it. because they cannot get a lock on the object (it is like door to the object).
How does other thread not able to execute the same task to run same method.
Because as long as one thread still holds the monitor, other threads wait. i.e, they cannot access the monitor themselves.So, they are blocked and will wait in the waiting set / queue for that object.
join is applied on that particular thread. But how does the second thread in the pipeline knows about the task has been done by first thread.
Join() ensures that the thread that calls join() on another thread, waits until the second thread completes its execution.
Note : A happens before relationship is established between the 2 threads when join is called. So that Whatever happens before a call to join or a return from join are always visible to other thread.
Edit :
Assume ThreadA and ThreadB are two threads running concurrently.
ThreadA
{
run(){
//some statements;
x=10; // assume x to be some shared variable
ThreadB.join();
// here ThreadA sees the value of "x" as 20. The same applies to synchronized blocks.
// Suppose ThreadA is executing in a Synchronized block of Object A, then after ThreadA //exits the synchronized block, then other threads will "always" see the changes made by //ThreadA
// some other statements
}
}
ThreadB{
run(){
//some statements
x=20;
}
check : Happens Before

Calling a synchronized method from of a synchronized method, both of the same object [duplicate]

This question already has answers here:
Is it safe to call a synchronized method from another synchronized method?
(3 answers)
Closed 9 years ago.
Why doesn't the code below lead to a deadlock? I mean after i call getNumber(.) the object of the class Test should be locked, so I shouldn't be able to access getNumber2(.).
class Test() {
synchronized int getNumber(int i){
return getNumber2(i);
}
synchronized int getNumber2(int i) {
return i;
}
public static void main(String[] args) {
System.out.println((new Test()).getNumber(100));
}
}
Output:
100
This is because the lock is re-entrant, meaning that it can be acquired multiple times by the same thread.
From the Java tutorial:
Reentrant Synchronization
Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.
The relevant part of the JLS is §17.1. Synchronization:
The Java programming language provides multiple mechanisms for communicating between threads. The most basic of these methods is synchronization, which is implemented using monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.
It doesn't lead to a deadlock because when a thread enter a synchronized method, what it does is checking that it has a lock on this, then if it doesn't, it waits until it can have the lock and get it.
When the thread enters the second synchonized method in your case, it already has the lock on the this object, so it can enter the method without blocking.

Difference between "wait()" vs "sleep()" in Java

What is the difference between a wait() and sleep() in Threads?
Is my understanding that a wait()-ing Thread is still in running mode and uses CPU cycles but a sleep()-ing does not consume any CPU cycles correct?
Why do we have both wait() and sleep()?
How does their implementation vary at a lower level?
A wait can be "woken up" by another thread calling notify on the monitor which is being waited on whereas a sleep cannot. Also a wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not:
Object mon = ...;
synchronized (mon) {
mon.wait();
}
At this point the currently executing thread waits and releases the monitor. Another thread may do
synchronized (mon) { mon.notify(); }
(on the same mon object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.
You can also call notifyAll if more than one thread is waiting on the monitor – this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait is in a synchronized block) and carry on – the others will then be blocked until they can acquire the monitor's lock.
Another point is that you call wait on Object itself (i.e. you wait on an object's monitor) whereas you call sleep on Thread.
Yet another point is that you can get spurious wakeups from wait (i.e. the thread which is waiting resumes for no apparent reason). You should always wait whilst spinning on some condition as follows:
synchronized {
while (!condition) { mon.wait(); }
}
One key difference not yet mentioned is that:
sleep() does not release the lock it holds on the Thread,
synchronized(LOCK) {
Thread.sleep(1000); // LOCK is held
}
wait() releases the lock it holds on the object.
synchronized(LOCK) {
LOCK.wait(); // LOCK is not held
}
I found this post helpful. It puts the difference between Thread.sleep(), Thread.yield(), and Object.wait() in human terms. To quote:
It all eventually makes its way down to the OS’s scheduler, which
hands out timeslices to processes and threads.
sleep(n) says “I’m done with my timeslice, and please don’t give me
another one for at least n milliseconds.” The OS doesn’t even try to
schedule the sleeping thread until requested time has passed.
yield() says “I’m done with my timeslice, but I still have work to
do.” The OS is free to immediately give the thread another timeslice,
or to give some other thread or process the CPU the yielding thread
just gave up.
wait() says “I’m done with my timeslice. Don’t give me another
timeslice until someone calls notify().” As with sleep(), the OS won’t
even try to schedule your task unless someone calls notify() (or one of
a few other wakeup scenarios occurs).
Threads also lose the remainder of their timeslice when they perform
blocking IO and under a few other circumstances. If a thread works
through the entire timeslice, the OS forcibly takes control roughly as
if yield() had been called, so that other processes can run.
You rarely need yield(), but if you have a compute-heavy app with
logical task boundaries, inserting a yield() might improve system
responsiveness (at the expense of time — context switches, even just
to the OS and back, aren’t free). Measure and test against goals you
care about, as always.
There are a lot of answers here but I couldn't find the semantic distinction mentioned on any.
It's not about the thread itself; both methods are required as they support very different use-cases.
sleep() sends the Thread to sleep as it was before, it just packs the context and stops executing for a predefined time. So in order to wake it up before the due time, you need to know the Thread reference. This is not a common situation in a multi-threaded environment. It's mostly used for time-synchronization (e.g. wake in exactly 3.5 seconds) and/or hard-coded fairness (just sleep for a while and let others threads work).
wait(), on the contrary, is a thread (or message) synchronization mechanism that allows you to notify a Thread of which you have no stored reference (nor care). You can think of it as a publish-subscribe pattern (wait == subscribe and notify() == publish). Basically using notify() you are sending a message (that might even not be received at all and normally you don't care).
To sum up, you normally use sleep() for time-syncronization and wait() for multi-thread-synchronization.
They could be implemented in the same manner in the underlying OS, or not at all (as previous versions of Java had no real multithreading; probably some small VMs doesn't do that either). Don't forget Java runs on a VM, so your code will be transformed in something different according to the VM/OS/HW it runs on.
Here, I have listed few important differences between wait() and sleep() methods.
PS: Also click on the links to see library code (internal working, just play around a bit for better understanding).
wait()
wait() method releases the lock.
wait() is the method of Object class.
wait() is the non-static method - public final void wait() throws InterruptedException { //...}
wait() should be notified by notify() or notifyAll() methods.
wait() method needs to be called from a loop in order to deal with false alarm.
wait() method must be called from synchronized context (i.e. synchronized method or block), otherwise it will throw IllegalMonitorStateException
sleep()
sleep() method doesn't release the lock.
sleep() is the method of java.lang.Thread class.
sleep() is the static method - public static void sleep(long millis, int nanos) throws InterruptedException { //... }
after the specified amount of time, sleep() is completed.
sleep() better not to call from loop(i.e. see code below).
sleep() may be called from anywhere. there is no specific requirement.
Ref: Difference between Wait and Sleep
Code snippet for calling wait and sleep method
synchronized(monitor){
while(condition == true){
monitor.wait() //releases monitor lock
}
Thread.sleep(100); //puts current thread on Sleep
}
Difference between wait() and sleep()
The fundamental difference is that wait() is non static method of Object and sleep() is a static method of Thread.
The major difference is that wait() releases the lock while sleep() doesn’t release any lock while waiting.
wait() is used for inter-thread communication while sleep() is used to introduce a pause on execution, generally.
wait() should be called from inside synchronise or else we get an IllegalMonitorStateException, while sleep() can be called anywhere.
To start a thread again from wait(), you have to call notify() or notifyAll() indefinitely. As for sleep(), the thread gets started definitely after a specified time interval.
Similarities
Both make the current thread go into the Not Runnable state.
Both are native methods.
There are some difference key notes i conclude after working on wait and sleep, first take a look on sample using wait() and sleep():
Example1: using wait() and sleep():
synchronized(HandObject) {
while(isHandFree() == false) {
/* Hand is still busy on happy coding or something else, please wait */
HandObject.wait();
}
}
/* Get lock ^^, It is my turn, take a cup beer now */
while (beerIsAvailable() == false) {
/* Beer is still coming, not available, Hand still hold glass to get beer,
don't release hand to perform other task */
Thread.sleep(5000);
}
/* Enjoy my beer now ^^ */
drinkBeers();
/* I have drink enough, now hand can continue with other task: continue coding */
setHandFreeState(true);
synchronized(HandObject) {
HandObject.notifyAll();
}
Let clarity some key notes:
Call on:
wait(): Call on current thread that hold HandObject Object
sleep(): Call on Thread execute task get beer (is class method so affect on current running thread)
Synchronized:
wait(): when synchronized multi thread access same Object (HandObject) (When need communication between more than one thread (thread execute coding, thread execute get beer) access on same object HandObject )
sleep(): when waiting condition to continue execute (Waiting beer available)
Hold lock:
wait(): release the lock for other object have chance to execute (HandObject is free, you can do other job)
sleep(): keep lock for at least t times (or until interrupt) (My job still not finish, i'm continue hold lock and waiting some condition to continue)
Wake-up condition:
wait(): until call notify(), notifyAll() from object
sleep(): until at least time expire or call interrupt
And the last point is use when as estani indicate:
you normally use sleep() for time-syncronization and wait() for
multi-thread-synchronization.
Please correct me if i'm wrong.
This is a very simple question, because both these methods have a totally different use.
The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.
This was just a clear and basic explanation, if you want more than that then continue reading.
In case of wait() method thread goes in waiting state and it won't come back automatically until we call the notify() method (or notifyAll() if you have more then one thread in waiting state and you want to wake all of those thread). And you need synchronized or object lock or class lock to access the wait() or notify() or notifyAll() methods. And one more thing, the wait() method is used for inter-thread communication because if a thread goes in waiting state you'll need another thread to wake that thread.
But in case of sleep() this is a method which is used to hold the process for few seconds or the time you wanted. Because you don't need to provoke any notify() or notifyAll() method to get that thread back. Or you don't need any other thread to call back that thread. Like if you want something should happen after few seconds like in a game after user's turn you want the user to wait until the computer plays then you can mention the sleep() method.
And one more important difference which is asked often in interviews: sleep() belongs to Thread class and wait() belongs to Object class.
These are all the differences between sleep() and wait().
And there is a similarity between both methods: they both are checked statement so you need try catch or throws to access these methods.
I hope this will help you.
source : http://www.jguru.com/faq/view.jsp?EID=47127
Thread.sleep() sends the current thread into the "Not Runnable" state
for some amount of time. The thread keeps the monitors it has aquired
-- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread.
Note that sleep is a static method, which means that it always affects
the current thread (the one that is executing the sleep method). A
common mistake is to call t.sleep() where t is a different thread;
even then, it is the current thread that will sleep, not the t thread.
t.suspend() is deprecated. Using it is possible to halt a thread other
than the current thread. A suspended thread keeps all its monitors and
since this state is not interruptable it is deadlock prone.
object.wait() sends the current thread into the "Not Runnable" state,
like sleep(), but with a twist. Wait is called on an object, not a
thread; we call this object the "lock object." Before lock.wait() is
called, the current thread must synchronize on the lock object; wait()
then releases this lock, and adds the thread to the "wait list"
associated with the lock. Later, another thread can synchronize on the
same lock object and call lock.notify(). This wakes up the original,
waiting thread. Basically, wait()/notify() is like
sleep()/interrupt(), only the active thread does not need a direct
pointer to the sleeping thread, but only to the shared lock object.
Wait and sleep are two different things:
In sleep() the thread stops working for the specified duration.
In wait() the thread stops working until the object being waited-on is notified, generally by other threads.
sleep is a method of Thread, wait is a method of Object, so wait/notify is a technique of synchronizing shared data in Java (using monitor), but sleep is a simple method of thread to pause itself.
sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().
The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution, generally.
Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired — i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
object.wait() sends the current thread into the “Not Runnable” state, like sleep(), but with a twist. Wait is called on an object, not a thread; we call this object the “lock object.” Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the “wait list” associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.
synchronized(LOCK) {
Thread.sleep(1000); // LOCK is held
}
synchronized(LOCK) {
LOCK.wait(); // LOCK is not held
}
Let categorize all above points :
Call on:
wait(): Call on an object; current thread must synchronize on the lock object.
sleep(): Call on a Thread; always currently executing thread.
Synchronized:
wait(): when synchronized multiple threads access same Object one by one.
sleep(): when synchronized multiple threads wait for sleep over of sleeping thread.
Hold lock:
wait(): release the lock for other objects to have chance to execute.
sleep(): keep lock for at least t times if timeout specified or somebody interrupt.
Wake-up condition:
wait(): until call notify(), notifyAll() from object
sleep(): until at least time expire or call interrupt().
Usage:
sleep(): for time-synchronization and;
wait(): for multi-thread-synchronization.
Ref:diff sleep and wait
In simple words, wait is wait Until some other thread invokes you whereas sleep is "dont execute next statement" for some specified period of time.
Moreover sleep is static method in Thread class and it operates on thread, whereas wait() is in Object class and called on an object.
Another point, when you call wait on some object, the thread involved synchronize the object and then waits. :)
wait and sleep methods are very different:
sleep has no way of "waking-up",
whereas wait has a way of "waking-up" during the wait period, by another thread calling notify or notifyAll.
Come to think about it, the names are confusing in that respect; however sleep is a standard name and wait is like the WaitForSingleObject or WaitForMultipleObjects in the Win API.
From this post : http://javaconceptoftheday.com/difference-between-wait-and-sleep-methods-in-java/
wait() Method.
1) The thread which calls wait() method releases the lock it holds.
2) The thread regains the lock after other threads call either notify() or notifyAll() methods on the same lock.
3) wait() method must be called within the synchronized block.
4) wait() method is always called on objects.
5) Waiting threads can be woken up by other threads by calling notify() or notifyAll() methods.
6) To call wait() method, thread must have object lock.
sleep() Method
1) The thread which calls sleep() method doesn’t release the lock it holds.
2) sleep() method can be called within or outside the synchronized block.
3) sleep() method is always called on threads.
4) Sleeping threads can not be woken up by other threads. If done so, thread will throw InterruptedException.
5) To call sleep() method, thread need not to have object lock.
Here wait() will be in the waiting state till it notify by another Thread but where as sleep() will be having some time..after that it will automatically transfer to the Ready state...
wait() is a method of Object class.
sleep() is a method of Thread class.
sleep() allows the thread to go to sleep state for x milliseconds.
When a thread goes into sleep state it doesn’t release the lock.
wait() allows thread to release the lock and goes to suspended state.
This thread will be active when a notify() or notifAll() method is
called for the same object.
One potential big difference between sleep/interrupt and wait/notify is that
calling interrupt() during sleep() always throws an exception (e.g. InterruptedException), whereas
calling notify() during wait() does not.
Generating an exception when not needed is inefficient. If you have threads communicating with each other at a high rate, then it would be generating a lot of exceptions if you were calling interrupt all the time, which is a total waste of CPU.
You are correct - Sleep() causes that thread to "sleep" and the CPU will go off and process other threads (otherwise known as context switching) wheras I believe Wait keeps the CPU processing the current thread.
We have both because although it may seem sensible to let other people use the CPU while you're not using it, actualy there is an overhead to context switching - depending on how long the sleep is for, it can be more expensive in CPU cycles to switch threads than it is to simply have your thread doing nothing for a few ms.
Also note that sleep forces a context switch.
Also - in general it's not possible to control context switching - during the Wait the OS may (and will for longer waits) choose to process other threads.
The methods are used for different things.
Thread.sleep(5000); // Wait until the time has passed.
Object.wait(); // Wait until some other thread tells me to wake up.
Thread.sleep(n) can be interrupted, but Object.wait() must be notified.
It's possible to specify the maximum time to wait: Object.wait(5000) so it would be possible to use wait to, er, sleep but then you have to bother with locks.
Neither of the methods uses the cpu while sleeping/waiting.
The methods are implemented using native code, using similar constructs but not in the same way.
Look for yourself: Is the source code of native methods available? The file /src/share/vm/prims/jvm.cpp is the starting point...
Wait() and sleep() Differences?
Thread.sleep()
Once its work completed then only its release the lock to everyone. until its never release the lock to anyone.
Sleep() take the key, its never release the key to anyone, when its work completed then only its release then only take the key waiting stage threads.
Object.wait()
When its going to waiting stage, its will be release the key and its waiting for some of the seconds based on the parameter.
For Example:
you are take the coffee in yours right hand, you can take another anyone of the same hand, when will your put down then only take another object same type here. also. this is sleep()
you sleep time you didn't any work, you are doing only sleeping.. same here also.
wait(). when you are put down and take another one mean while you are waiting , that's wait
you are play movie or anything in yours system same as player you can't play more than one at a time right, thats its here, when you close and choose another anyone movie or song mean while is called wait
wait releases the lock and sleep doesn't. A thread in waiting state is eligible for waking up as soon as notify or notifyAll is called. But in case of sleep the thread keeps the lock and it'll only be eligible once the sleep time is over.
sleep() method causes the current thread to move from running state to block state for a specified time. If the current thread has the lock of any object then it keeps holding it, which means that other threads cannot execute any synchronized method in that class object.
wait() method causes the current thread to go into block state either for a specified time or until notify, but in this case the thread releases the lock of the object (which means that other threads can execute any synchronized methods of the calling object.
In my opinion, the main difference between both mechanisms is that sleep/interrupt is the most basic way of handling threads, whereas wait/notify is an abstraction aimed to do thread inter-communication easier. This means that sleep/interrupt can do anything, but that this specific task is harder to do.
Why is wait/notify more suitable? Here are some personal considerations:
It enforces centralization. It allows to coordinate the communication between a group of threads with a single shared object. This simplifies the work a lot.
It enforces synchronization. Because it makes the programmer wrap the call to wait/notify in a synchronized block.
It's independent of the thread origin and number. With this approach you can add more threads arbitrarily without editing the other threads or keeping a track of the existing ones. If you used sleep/interrupt, first you would need to keep the references to the sleeping threads, and then interrupt them one by one, by hand.
An example from the real life that is good to explain this is a classic restaurant and the method that the personnel use to communicate among them: The waiters leave the customer requests in a central place (a cork board, a table, etc.), ring a bell, and the workers from the kitchen come to take such requests. Once that there is any course ready, the kitchen personnel ring the bell again so that the waiters are aware and take them to the customers.
Example about sleep doesn’t release lock and wait does
Here there are two classes :
Main : Contains main method and two threads.
Singleton : This is singleton class with two static methods getInstance() and getInstance(boolean isWait).
public class Main {
private static Singleton singletonA = null;
private static Singleton singletonB = null;
public static void main(String[] args) throws InterruptedException {
Thread threadA = new Thread() {
#Override
public void run() {
singletonA = Singleton.getInstance(true);
}
};
Thread threadB = new Thread() {
#Override
public void run() {
singletonB = Singleton.getInstance();
while (singletonA == null) {
System.out.println("SingletonA still null");
}
if (singletonA == singletonB) {
System.out.println("Both singleton are same");
} else {
System.out.println("Both singleton are not same");
}
}
};
threadA.start();
threadB.start();
}
}
and
public class Singleton {
private static Singleton _instance;
public static Singleton getInstance() {
if (_instance == null) {
synchronized (Singleton.class) {
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
public static Singleton getInstance(boolean isWait) {
if (_instance == null) {
synchronized (Singleton.class) {
if (_instance == null) {
if (isWait) {
try {
// Singleton.class.wait(500);//Using wait
Thread.sleep(500);// Using Sleep
System.out.println("_instance :"
+ String.valueOf(_instance));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
_instance = new Singleton();
}
}
}
return _instance;
}
}
Now run this example you will get below output :
_instance :null
Both singleton are same
Here Singleton instances created by threadA and threadB are same. It means threadB is waiting outside until threadA release it’s lock.
Now change the Singleton.java by commenting Thread.sleep(500); method and uncommenting Singleton.class.wait(500); . Here because of Singleton.class.wait(500); method threadA will release all acquire locks and moves into the “Non Runnable” state, threadB will get change to enter in synchronized block.
Now run again :
SingletonA still null
SingletonA still null
SingletonA still null
_instance :com.omt.sleepwait.Singleton#10c042ab
SingletonA still null
SingletonA still null
SingletonA still null
Both singleton are not same
Here Singleton instances created by threadA and threadB are NOT same because of threadB got change to enter in synchronised block and after 500 milliseconds threadA started from it’s last position and created one more Singleton object.
Should be called from synchronized block : wait() method is always called from synchronized block i.e. wait() method needs to lock object monitor before object on which it is called. But sleep() method can be called from outside synchronized block i.e. sleep() method doesn’t need any object monitor.
IllegalMonitorStateException : if wait() method is called without acquiring object lock than IllegalMonitorStateException is thrown at runtime, but sleep() method never throws such exception.
Belongs to which class : wait() method belongs to java.lang.Object class but sleep() method belongs to java.lang.Thread class.
Called on object or thread : wait() method is called on objects but sleep() method is called on Threads not objects.
Thread state : when wait() method is called on object, thread that holded object’s monitor goes from running to waiting state and can return to runnable state only when notify() or notifyAll() method is called on that object. And later thread scheduler schedules that thread to go from from runnable to running state.
when sleep() is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up.
When called from synchronized block : when wait() method is called thread leaves the object lock. But sleep() method when called from synchronized block or method thread doesn’t leaves object lock.
For More Reference
From oracle documentation page on wait() method of Object:
public final void wait()
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up
interrupts and spurious wakeups are possible
This method should only be called by a thread that is the owner of this object's monitor
This method throws
IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.
InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
From oracle documentation page on sleep() method of Thread class:
public static void 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.
The thread does not lose ownership of any monitors.
This method throws:
IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
Other key difference:
wait() is a non-static method (instance method) unlike static method sleep() (class method).
wait() is given inside a synchronized method
whereas sleep() is given inside a non-synchronized method because wait() method release the lock on the object but sleep() or yield() does release the lock().
The method wait(1000) causes the current thread to sleep up to one second.
A thread could sleep less than 1 second if it receives the notify() or notifyAll() method call.
The call to sleep(1000) causes the current thread to sleep for exactly 1 second.
Also sleeping thread doesn't hold lock any resource. But waiting thread does.
Actually, all this is clearly described in Java docs (but I realized this only after reading the answers).
http://docs.oracle.com/javase/8/docs/api/index.html :
wait() - The current thread must own this object's monitor. 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.
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 does not lose ownership of any monitors.

Categories

Resources