Why thread not going into waiting status for infinite time? - java

Below is the code piece which successfully finishes the execution when I run it in my local machine.
I cannot understand why this thread is not going into infinite wait status ?
public class Job extends Thread {
private int counter;
#Override
public void run() {
synchronized (this) {
for (int i = 0; i < 100000; i++) {
counter++;
}
this.notifyAll();
}
}
public static void main(String[] args) throws InterruptedException {
Job job = new Job();
job.start();
synchronized (job) {
job.wait();
}
System.out.println(job.counter);
}
}
Is there any gurantee that above code will always finish execution in every condition ? Can anybody clarify ?

It sure looks like you have a Race Condition on your hands - it all depends on which synchronized(job) happens first - the one in your main thread or the one in the job.

I cannot understand why this thread is not going into infinite wait
status ?
It can, and it will happen if this.notifyAll() is called before job.wait().
Add a flag to test for completion, something like the following:
public class Job extends Thread {
private int counter;
private boolean finished = false;
#Override
public void run() {
synchronized (this) {
for (int i = 0; i < 100000; i++) {
counter++;
}
finished = true;
this.notifyAll();
}
}
public static void main(String[] args) throws InterruptedException {
Job job = new Job();
job.start();
synchronized (job) {
while (!job.finished)
job.wait();
}
System.out.println(job.counter);
}
}
That way you can guarantee that the program will not run into a race condition and will wait forever. Also note that you are now protected against spurious wakeups.

There are a few possibilities
The main Thread enters the synchronized first and wait()s. In this case, the program will terminate because the job Thread will call notify() on the synchronized object.
The job Thread enters the synchronized block first and calls notify() before the main Thread calls wait(), ie. main Thread can't because it waits at the synchronized block. This will block the application as the main Thread will not be able to return from the wait() call.

Apart from the spurious wakeup issues (which should not affect this simple use most of the time), you should expect that code to always finish.
One thing you seem to be missing is that job.wait(); releases the lock, enabling the other synchronized block to be executed and notifyAll() to be called. At that point, wait wakes up and the main method exits.

Related

Creating a class that mimics a semaphore but the number of permits should never exceed 0

I came across a problem to design a queue using a semaphore such that all threads that acquire it must wait until some thread releases them. But the catch here is that if release is called when no thread is waiting then it should not have any effect unlike a real semaphore where an extra permit will be added. I started trying something like this:
public class QueueOfThreads {
private Semaphore valve = new Semaphore(0);
volatile int count = 0;
public void acquire() throws InterruptedException {
synchronized(this) {
count++;
}
valve.acquire();
}
public void release() {
synchronized(this) {
if(count > 0) {
valve.release();
count--;
}
else {
System.out.println("will not release since no thread is waiting");
}
}
}
}
But I can see that this is wrong since if a thread is preempted after count++ then the release can be called before acquire.
I spent a lot of time trying to find a way to make sure that at least one acquire is called before any release. But I always end up with the same problem, I can not signal to other threads about acquiring the semaphore after the semaphore is acquired since the current thread will be in waiting state. But if I signal before acquiring the semaphore then the thread can be preempted before the semaphore is actually acquired.
Please let me know if writing a class like this is possible and how to do it?
This problem came to me from a comment in a book called "The Little Book of Semaphores" By Allen B. Downey where it is mentioned that:
"Semaphores can also be used to represent a queue. In this case, the initial value is 0, and usually the code is written so that it is not possible to signal unless there is a thread waiting, so the value of the semaphore is never positive."
You can exploit Object.notify() which frees exactly one waiting thread, if any:
public class QueueOfThreads {
public synchronized void acquire() throws InterruptedException {
wait();
}
public synchronized void release() {
notify();
}
}
However, this works only on JVM without spurious wakeups.
If spurious wakeup can happen, then the implementation is more complex:
public class QueueOfThreads {
int threadCount = 0;
boolean notified = false;
public synchronized void acquire() throws InterruptedException {
threadCount++;
do {
wait();
} while (!notified);
threadCount--;
notified = false;
}
public synchronized void release() {
if (threadCount==0) {
return;
}
notified = true;
notify();
}
}

Daemon thread with infinite loop not terminating

I have a simple test program (garage simulation) with several threads (Vehicle, MysteryVehicle, Observer objects) instantiated and started. Only the Observer object is a daemon thread running an infinite loop.
After all non-daemon threads terminate, Observer thread never does and the loop is executed infinitely (so this isn't some buffered output after the daemon thread really terminates - it does go on forever).
All of the non-daemon threads print something to the console just before exiting their run() methods, and it clearly shows all of them really terminated. I also didn't call join() on the daemon thread. When printing out all currently running threads, observer is listed as well, so my guess is that this daemon thread isn't terminating properly.
The complete code can be found on this commit.
Below you can see all threads created, started and where exactly is join() called.
Main.java
package garage;
import java.util.Set;
import garage.model.*;
import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
Platform platform = new Platform();
Vehicle.platform = platform;
platform.print();
Vehicle[] vehicles = new Vehicle[30];
for (int i = 0; i < 30; i++) {
vehicles[i] = new Vehicle();
}
for (int i = 0; i < 30; i++) {
vehicles[i].start();
}
Observer observer = new Observer();
observer.platform = platform;
observer.start();
MysteryVehicle mysteryVehicle = new MysteryVehicle();
mysteryVehicle.start();
try {
mysteryVehicle.join();
} catch (Exception exception) {
exception.printStackTrace();
}
try {
for (int i = 0; i < 30; i++)
vehicles[i].join();
} catch (Exception exception) {
exception.printStackTrace();
}
System.out.println("before");
platform.print();
System.out.println("after");
synchronized (Platform.lock) {
System.out.println("END");
System.out.println(platform.flag); // checks whether wait() was called anytime
}
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread t : threads) {
System.out.println(t.getName());
}
}
public static void main(String[] args) {
launch(args);
}
}
Observer.java
package garage.model;
public class Observer extends Thread {
public Platform platform;
static int count = 0;
{
setName("observer");
setPriority(MIN_PRIORITY);
setDaemon(true);
}
#Override
public void run() {
while (true) {
synchronized (Platform.lock) {
try {
System.out.println(++count);
platform.print();
Platform.lock.wait(5000); // hack for when there is no meaningful loop condition
} catch (InterruptedException exception) {
exception.printStackTrace();
} finally {
Platform.lock.notifyAll();
}
}
}
}
}
Vehicle run() method - relevant part
public void run() {
...
System.out.println("done");
}
MysteryVehicle run() method - relevant part
public void run() {
synchronized (Platform.lock) {
System.out.println("And the vehicle disappears!");
...
}
}
All of the relevant thread messages are printed out to the console.
done - 30 times, And the vehicle disappears!, before, after, END, true
This is the list of all of the running threads:
Attach Listener
main
Common-Cleaner
JavaFX Application Thread
Signal Dispatcher
Finalizer
InvokeLaterDispatcher
Reference Handler
QuantumRenderer-0
observer
Thread-2
JavaFX-Launcher
Since the program doesn't terminate and the print() function the run() method of observer calls is executed infinitely, what is it that prevents the daemon thread from terminating?
What am I missing here?
I suspect main() never returns, so the main thread (and perhaps some of those FX threads) are still running.
From the Application doc:
The launch method does not return until the application has exited,
either via a call to Platform.exit or all of the application windows
have been closed.
The posted code has no window to close nor is Platform.exit() invoked.
As far as I know, calling join on daemon thread is a bad idea.The idea behind using daemon thread is it will not halt JVM from exiting. What you can do is send an interrupt to that thread and call join after that.

Destroying a thread, having a never ending function int its run() method?

In my run() method of my Thread class, I am calling a never ending function.
I need the thread to run only for a specific duration.
Am not able to control the thread once its started, Is their any way to destroy it?
I have tried yield(), sleep(), etc...
PS - I cannot change the never ending function
From oracle Java Docs:
public void run(){
for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}
}
Your thread should check interrupted condition after each loop to see if it was interrupted. If you are calling a method that just does while(true){} then I am afraid there is no way interrupting it and stop() MUST never be called on a thread.
It is the programmers responsibility to make a long running method responsive to interrupts.
http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html answers all your questions.. particularly section What should I use instead of Thread.stop?
Hope it helps
This could be too much, but this is how I would solve it, if you do not want to mess with Interrupt.
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
ThreadTest test = new ThreadTest();
test.go();
}
void go() throws InterruptedException{
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(new LongRunnable());
if(!service.awaitTermination(1000, TimeUnit.MILLISECONDS)){
System.out.println("Not finished within interval");
service.shutdownNow();
}
}
}
class LongRunnable implements Runnable {
public void run(){
try{
//Simultate some work
Thread.sleep(2000);
} catch(Exception e){
e.printStackTrace();
}
}
}
Basically you are wrapping your runnable in a ExecutorServie and if it's not finished within the interval, you basically kill it - send the interruption to it.

I was searching for stopping java thread gracefully and found that, but I cannot know how to check example of this situation

This is good example of stopping thread.
How to stop a java thread gracefully?
But when I try to check this example I received infinite loop.
This is my code:
public class Num {
public void crash(ManualStopping t1) {
t1.stopMe();
}
public static void main(String[] args) {
Num num = new Num();
ManualStopping t1 = new ManualStopping();
t1.run();
System.out.println("Main thread");
num.crash(t1);
}
}
class ManualStopping extends Thread {
volatile boolean finished = false;
public void stopMe() {
finished = true;
}
public void run() {
while (!finished) {
System.out.println("I'm alive");
}
}
}
I think you need to start your thread - not run it. By calling run, you are just making a normal method call, not running a separate thread.
Nothing in your code calls the stopMe method on ManualStopping. isInterrupted() is a test that doesn't change the state of the thread. And as #DaveHowes points out, you don't even start a separate thread.
t1.run(); Change it to t1.start().
Whats happening is that the thread you intend to spawn is not actually running as a separate thread. Instead the loop
while(!finished){ System.out.println("I'm alive"); }
is running on the main thread and your code num.crash(t1); never actually gets invoked. This is causing the infinite loop.

I just wonder why it have to join threads in the second loop

When writing code like:
public class TestBasic {
public static void print(Object o){
System.out.println(o);
}
public static void main(String...strings) throws InterruptedException {
Thread[] threads = new Thread[5];
for(int i=0;i<5;i++){
Thread thread = new Thread(new LittleRunner());
thread.start();
thread.join();
}
}
}
class LittleRunner implements Runnable{
public void run() {
for(int i=1;i<10;i++){
TestBasic.print(Thread.currentThread().getName()+":"+i);
}
}
}
And the output is:
Thread-0:1
Thread-0:2
...
Thread-4:8
Thread-4:9
Which means sequentially printing out. So, does somebody know the reason?
Thanks a lot and Best regards.
You're joining each thread before starting the next thread.
At any single point in time, there will only be one thread running, because you already waited for the previous thread to finish.
You need to start all of the threads before waiting for the first one to finish.
Change the main method to:
public static void main(String...strings) throws InterruptedException {
Thread[] threads = new Thread[5];
for(int i=0;i<5;i++){
threads[i] = new Thread(new LittleRunner());
threads[i].start();
}
for(int i=0;i<5;i++){
threads[i].join;
}
}
Basically, thread.start() will start the thread in background and move on. Then, when you do a thread.join(), the execution will stop until thread is finished. So, in your version of the program, you were starting each thread and then waiting for it to finish before starting the next thread, hence the sequential execution.

Categories

Resources