I have a confusion. I read somewhere that Thread.yield() method causes the currently running thread to pause and give chance to remaining thread of "Same Priority".
Now always it is same priority threads executed or higher priority threads can also be executed. And if suppose currently running thread has some lock on some object, after executing yeild method will it give its lock?
When you call Thread.yield() the current thread pauses and allows the scheduler to run a different thread. Priorities are managed by the scheduler.
And no, of course not - you don't release any locks. Doing so would break synchronization.
Related
If you are running multiple threads all with the same priority, why do you not need to call the yield or sleep method in any of the threads? I must have misunderstood how threading works. I was under the assumption that if two threads are of the same priority, one will finish before the other is started on a single core system. That is, unless you call one of the control functions ie.) yield() sleep() join() ... ect
Anyone with the knowledge of this subject I would appreciate any clarifications you may have for me.
StackOverFlow would not let me add a comment to your answer:
Also according to my book: "The JVM always picks the currently runnable thread with the highest priority. A lower priority thread can run only when no higher-priority threads are running."
why do you not need to call the yield or sleep method in any of the threads?
Scheduling is done pre-emptively. You don't need to call yield or sleep or wait or call a blocking operation for the OS to suspend you thread.
I was under the assumption that if two threads are of the same priority, one will finish before the other is started on a single core system.
Even if one thread is maximum priority and one is the lowest priority, it doesn't mean one will finish before the other.
unless you call one of the control functions ie.) yield() sleep() join()
Calling these methods can give up the CPU but this doesn't mean the OS won't suspect a thread because these were not called., note: they don't have to.
So far what I have understood about wait() and yield () methods is that yield() is called when the thread is not carrying out any task and lets the CPU execute some other thread. wait() is used when some thread is put on hold and usually used in the concept of synchronization. However, I fail to understand the difference in their functionality and i'm not sure if what I have understood is right or wrong. Can someone please explain the difference between them(apart from the package they are present in).
aren't they both doing the same task - waiting so that other threads can execute?
Not even close, because yield() does not wait for anything.
Every thread can be in one of a number of different states: Running means that the thread is actually running on a CPU, Runnable means that nothing is preventing the thread from running except, maybe the availability of a CPU for it to run on. All of the other states can be lumped into a category called blocked. A blocked thread is a thread that is waiting for something to happen before it can become runnable.
The operating system preempts running threads on a regular basis: Every so often (between 10 times per second and 100 times per second on most operating systems) the OS tags each running thread and says, "your turn is up, go to the back of the run queue' (i.e., change state from running to runnable). Then it lets whatever thread is at the head of the run queue use that CPU (i.e., become running again).
When your program calls Thread.yield(), it's saying to the operating system, "I still have work to do, but it might not be as important as the work that some other thread is doing. Please send me to the back of the run queue right now." If there is an available CPU for the thread to run on though, then it effectively will just keep running (i.e., the yield() call will immediately return).
When your program calls foobar.wait() on the other hand, it's saying to the operating system, "Block me until some other thread calls foobar.notify().
Yielding was first implemented on non-preemptive operating systems and, in non-preemptive threading libraries. On a computer with only one CPU, the only way that more than one thread ever got to run was when the threads explicitly yielded to one another.
Yielding also was useful for busy waiting. That's where a thread waits for something to happen by sitting in a tight loop, testing the same condition over and over again. If the condition depended on some other thread to do some work, the waiting thread would yield() each time around the loop in order to let the other thread do its work.
Now that we have preemption and multiprocessor systems and libraries that provide us with higher-level synchronization objects, there is basically no reason why an application programs would need to call yield() anymore.
wait is for waiting on a condition. This might not jump into the eye when looking at the method as it is entirely up to you to define what kind of condition it is. But the API tries to force you to use it correctly by requiring that you own the monitor of the object on which you are waiting, which is necessary for a correct condition check in a multi-threaded environment.
So a correct use of wait looks like:
synchronized(object) {
while( ! /* your defined condition */)
object.wait();
/* execute other critical actions if needed */
}
And it must be paired with another thread executing code like:
synchronized(object) {
/* make your defined condition true */)
object.notify();
}
In contrast Thread.yield() is just a hint that your thread might release the CPU at this point of time. It’s not specified whether it actually does anything and, regardless of whether the CPU has been released or not, it has no impact on the semantics in respect to the memory model. In other words, it does not create any relationship to other threads which would be required for accessing shared variables correctly.
For example the following loop accessing sharedVariable (which is not declared volatile) might run forever without ever noticing updates made by other threads:
while(sharedVariable != expectedValue) Thread.yield();
While Thread.yield might help other threads to run (they will run anyway on most systems), it does not enforce re-reading the value of sharedVariable from the shared memory. Thus, without other constructs enforcing memory visibility, e.g. decaring sharedVariable as volatile, this loop is broken.
The first difference is that yield() is a Thread method , wait() is at the origins Object method inheritid in thread as for all classes , that in the shape, in the background (using java doc)
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).
yield()
A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
and here you can see the difference between yield() and wait()
Yield(): When a running thread is stopped to give its space to another thread with a high priority, this is called Yield.Here the running thread changes to runnable thread.
Wait(): A thread is waiting to get resources from a thread to continue its execution.
When I was going through Javadoc for CountDownLatch, I came across a line in the documentation for await method.
If the current count is greater than zero then the current thread
becomes disabled for thread scheduling purposes and lies dormant
What is meant by current thread becomes disabled for thread scheduling purposes here?
On a given system, only a fixed number of threads can actually execute at the same time (you're limited by the number of cores in the machine.) When there are more threads to run than there are cores, the thread scheduler will cycle through the threads in some fashion, giving each a bit of time on the CPU.
However, in some cases it doesn't make sense to give a thread time on the CPU. For example, if a thread acquires a countdown latch whose total is greater than zero, then that thread is stuck waiting for other threads to also acquire the latch. It therefore doesn't make any sense to let that thread have any CPU time, since the thread is just sitting and waiting for other threads. Therefore, typically, the scheduler would not even attempt to give the thread any CPU time, preferring instead to schedule other threads that can still make progress. Once enough threads do acquire the countdown latch, all threads that were blocked this way are then put back into the scheduler for further consideration.
In other words, the thread stops running and the scheduler will intelligently not waste time trying to run it until the latch is ready.
Hope this helps!
It just means that the code in that thread will not go any further until latch.countDown() is called on the same latch from other threads thereby making the latch count 0.
A thread runs when it is in runnable state and the scheduler schedules it. When a threads is disabled for scheduling, it will not get its share of cpu cycles, so it wont run which means its program counter will not increase. Its stack will freeze where it was till it gets the cpu again.
i've got an application with a possible number of threads. basicly the threads should work this:
Main Thread
CalculationThread
CalculationThread
CalculationThread
Adding / Executing those threads to a FixedThreadPool isn't the problem. The Thread itself calls a certain function in the Mainthread to submit the results. After this step, the thread should sleep until it will be called again for the next calucation.
The Mainthread holds a reference to a CalculationThread to submit updates to the thread and readd it to the pool to start the next calculation.
My Problem: How can I enforce a timeout for a certain thread? The enforcement of this timeout must also work, if a endless loop occurs
You cannot enforce the timeout without cooperation from the thread, at least not in a sane way. You should code your calculation tasks so that they comply with the Java interruption mechanism. Basically, that means occasionally checking the Thread.interrupted return value and aborting on true.
The only other option is the ham-handed – and deprecated – Thread.stop, which can wreak general chaos, especially when done on a pool-managed thread.
I was asked this question in an interview - not sure if it makes sense.
You have several threads of same priority started and running, how do you make sure that a particular thread among those is run to completion first?
You can't use wait() and sleep() trick on other threads..
EDIT:
Modifying the other threads is not allowed.
have one thread join() the other
Since you are not allowed to modify the threads, you will have to suspend the waiting threads and join() on the thread that must complete first.
I'll leave the following (I answered before the clarification about modifying the threads was added) for completeness, but under the clarified constraints of the problem these methods would be disallowed:
Have each of the other threads call join() on the thread that should complete first. This will cause them to wait until that thread has terminated, but using considerably less CPU time than a sleep() loop would.
Thread first = new FirstThread();
Thread after1 = new AfterThread(first);
Thread after2 = new AfterThread(first);
In the run method for AfterThread:
first.join();
// Do the rest of this thread's code
You can also pass a timeout to join().
An alternative method might be to create a lock that only a particular named thread can acquire, until after that named thread has acquired and released it once.
It's deprecated and inherently unsafe (so you should never use it), but you could suspend() all the other threads, then join() on the one you want to finish first, then resume().
I'm not sure if that's what they're going for. If it is, I would doubt either their interview skills or their Java knowledge.
The "good" solutions that I can think of require at least trivially modifying the code that the threads are going to run. Are you sure that it is off limits to modify those threads?