This is one question, asked to me a interview, on which I have no idea what he is asking.
If you can help on the same:
sleep, wait, notify, yield - which one is a callback?
None of the methods you list are callbacks. The entire Thread class contains only one user-overridable method, and that is run, which may be considered a callback method for that class because it is called by Thread's internals. However, a best practice is not to extend Thread at all. Supply your own Runnable implementation, which has its callback run method.
None of those look like traditional callbacks. A callback function/method is something you register to be called once an operation is complete (possibly asynchronously if the task is scheduled in another thread).
Sleep, wait and yield essentially block execution until their conditions are met. Notify wakes threads blocked by wait.
A callback is a method that is created to be called at a certain time/event from elsewhere.
sleep(), wait(), and yield() are called by the thread to perform an action. notify() may be interpreted as one, and as such is the more correct answer if one is correct, though none are.
Related
Say that blockAndDoSomeLongWork() is a method that blocks. Usually, we'd perform it on another thread:
someExecutorService.execute(() -> {
blockAndDoSomeLongWork();
});
Question is: is there a way to notify a thread that i've called blockAndDoSomeLongWork() after the fact so that i will be absolutely sure that the other thread won't do anything before blockAndDoSomeLongWork() has been called? If i simply wake up the other thread via call in the lambda's body that immediately precedes blockAndDoSomeLongWork(), this makes it possible for the other thread to execute an action before blockAndDoSomeLongWork() was called, which is something i want to avoid.
Use a semaphore:
Semaphore sema = new Semaphore(0);
This thread:
someExecutorService.execute(() -> {
blockAndDoSomeLongWork();
sema.release();
});
Other thread:
sema.acquire();
// when we get here, the 'long work' has completed
This assumes there is exactly one 'other' thread, and rather more subtly, assumes that the 'long work' is a one-time thing. Otherwise you might need two-way interlocking.
No, this is impossible. It's hard to imagine why you would ever need it.
Let's say there was a notifyOtherThreadAndBlock() call.
This call would notify the other thread and then block.
But, this call has code in it. It notifies the other thread, then it blocks. What if your thread gets stopped after the notifying, and before the blocking? This is the same problem you already had. Putting it into a function didn't solve anything.
Now, it is theoretically possible. Maybe the operating system could have a function that says "hey, next time I block, please notify this other thread for me." But operating systems don't have that function. Why not? Because it's useless. You're supposed to just notify the other thread before you start blocking, because it doesn't make any difference anyway.
If it does make a difference, then your code is doing something wrong, and you should explain your situation better, so we can explain how to make it so you can notify before blocking.
Trying to understand wait() and notify(). I know when thread A went to wait() it will be waked up by notify() from other thread.
But what will happens if threads A,B,C went to wait() in represented order? Who will be waked up by notify()? According to my experiments A thread will be waked up at first. I'm right?
Does it means that system knows in which order threads went to wait() ?
From the documentation for notify(), emphasis mine:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
Some other APIs, such as Semaphore, have a concept of "fairness", where you can ensure that threads do proceed in the order in which they blocked.
Section 17.2.2 Notification of Java Language Specification:
There is no guarantee about which thread in the wait set is selected.
So, observed behavior is not guaranteed and should not be relied upon.
No, the VM does not know in which order the threads were put in Waiting state.
When you call notify(), one of them will be back to Alive/Runnable state and there is no way to know which one the VM will choose.
Sometimes they can run in the order they were put in Waiting state, but the specification does not guarantee that. So in a different VMs you can have a completely different results or even in the same VM, if you run the code multiple times.
No, there is no guarantee about the order. The javadoc of the notify method is pretty clear on this:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
There's no such an order. Either thread has an equal opportunity to get into runnable state. Actually JVM/OS can see them only as a set of waiting threads, they don't know any order.
In terms of your experiment, to get into a fair conclusion, actually you have to perform it for a huge number of times.
In threads, you can expect an order (FIFO), only if you are using something like a strong Semaphore. Then these threads are put into a waiting queue and fist comer would be first served.
What is the cost associated with calling notify() on an Object on which no other Objects have called wait() in Java?
The reason I am interested in this is because I have a worker thread that has a queue of Objects.
The thread loops continuously checking if it has any Objects in the queue that it needs to work with. If it loops and there is nothing in said queue the thread calls wait on on a separate Object.
When another thread adds an Object to the queue it calls notify on the Object that the worker thread would be waiting on regardless if the working thread is actually waiting.
Before anyone says anything, it is all synchronized correctly and won't throw any exceptions/errors.
My question is: is this setup slower then just having the worker thread just continue checking and never call wait() and what is the cost of calling notify() without any threads waiting on the Object?
Thanks for the help in advance :)
If you don't block worker thread, it'll be a busy-wait "spinloop" pattern, e.g. something like:
while (queue.isEmpty()) {
Thread.yield();
}
I've been reading about this model of conditional waiting today (in regards of my own problem :)) and found the following notes about when such model might show superior performance to ordinary wait() - notify() scheme:
... The main exceptions are those cases in which you somehow know that the condition must become true within some very short, boudned amount of time. In such cases, the time wasted spinning might be less than the time required to suspend and resume threads.
The book is "Concurrent Programming in Java: Design Principles and Patterns" by Doug Lea.
I have few threads that performs an actvity in parallel. I would have to proceed with the subsequent actvity only after all the threads are completed. Is there a way to achieve this?
You should take a look at the join() method in the Thread class. A join can be used to allow one thread to wait for another to complete. It's also overloaded to allow for the specification of a time to wait for the other thread to finish. Joins are discussed as part of the Java Tutorial on Concurrency.
for all threads do thread.join().
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()
You can use Thread.join() in order to cause a wait until thread completion. Take a look at the Javadoc for more information.
I think using a http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html is actually preferable over Thread.join() as it should scale better.
Conceptually, a way to address your problem is to create an observer object which will be referenced by every threads you are running. Once a thread is done it notifies the observer that it performed his task. Each time the Observer receive this kind of notification, it increment a counter, once the counter reach the number of threads, this means that all the threads are completed. then the Observer can start the final task.
That is for the theory. If you want there is a built-in java class for that: CountDownLatch
I'm synchronizing on the object of the thread like this:
synchronized(threadObject){
try{
threadObject.interrupt();
}catch(Exception ex){
//catch error here.
}finally{
threadObject.notifyAll();
}
}
Now, my questions are:
It is possible to interrupt a thread
inside a synchronized block whose
object that was synchronized was the
thread to be interrupted? Like in
the sample code.
Can I still notify other threads
holding the interrupted thread's
object? Like in the sample code.
It is possible to interrupt a thread inside a synchronized block whose object that was synchronized was the thread to be interrupted? Like in the sample code.
Yes. I can't see why that wouldn't work. The synchronized keyword is quite orthogonal to the interrupt method. (Note that contrary to await and notify, you're not required to own the objects monitor when calling interrupt.)
Can I still notify other threads holding the interrupted thread's object? Like in the sample code.
Yes, you can call notifyAll on any object as long as you own the objects monitor. Again, the wait/notify-mechanism is quite orthogonal to the interrupt method.
Your question seem to indicate that you've misunderstood the use of synchronized. The usual use-case is to synchronize on an object representing some resource which you like to avoid concurrent access to. The thread itself rarely represent such resource.
The object works as it normally does. The only stipulation is that other threads that synchronize on threadObject's monitor will block until you're complete with your thread. So yes, you can do both of those.
Yes: But you don't really need to have the lock before calling interrupt.
Yes
The answer to both questions is yes.
However, there is something a bit strange about your example. I've never come across a case where you would use a Thread as a primitive lock. And it what you are doing in the example doesn't seem to achieve anything.
If threadObject is the same as Thread.currentThread(), then the call to interrupt() will just set this thread's interrupted flag ... which be noticed in that code fragment.
if threadObject is some other Thread object then that thread will be interrupted. But we can't see (here) the code that that thread will be executing, and we don't know if it will be waiting on threadObject. If not the interrupt() and notify() well got to different threads ...
The bottom line is that you wouldn't normally use a Thread object as a lock, and you wouldn't normally send use an interrupt() as an ersatz notify().
(Maybe this example is not intended to represent a real use-case.)