How to "try start" one thread from several other threads, java - java

I wrote this in my function:
if(myThread.isAlive()) {
} else {
myThread.start();
}
but this is unsafe if many threads call this function the same time. start a running thread throws an exception.
So except putting try-catch around it, do I have other options?

Make this method synchronized. Also, this check (isAlive()) is unsafe because if the thread have been finished you cannot start it again (and isAlive() will return false...)

I would only create the thread when I intend to start it.
What you can do is
synchronized(thread) {
if(thread.getState() == Thread.State.NEW)
thread.start();
}
A thread which has finished will not be alive, but it cannot be retstarted.

Use a syncronized method / block? Use locks?

contrary on what everyone might tell: do not use isAvile() or getState(), both require to execute them into a sync. block along w/ thread.start() and requires that the thread actually uses itself as monitor (de-facto it does so)
instead, just catch the exception (IllegalThreadStateException) of start() and ignore it.
try{
thread.start()
}catch(IllegalThreadStateException _x){
//ignore or log the reason, use getState(), if need be
}

Related

what happen if using wait and notify methods not in a synchronized blocks ? is it useful?

Two questions regarding synchronization
What happen if using wait and notify methods in non synchronized blocks ? Is it useful ?
Should synchronized object be the same as the object of the wait method ? Can I do like this :
synchronized (o) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
An IllegalThreadStateException is thrown if the current thread fails to synchronize on an object before calling its wait() or notify() methods. So, no, it isn't useful.
Yes, to reiterate the above, the thread must synchronize on the same instance upon which it invokes wait() or notify(). So the example will only work if o == this.
I don't find good reasons to use wait() and notify() since java.util.concurrent was introduced, and synchronized is less useful now too. I recommend the higher-level tools in that package to both beginners (as easier to use) and advanced (more powerful and correct) programmers.
1.
You can't call wait() or notify()/notifyAll() outside of synchronized blocks that synchronize on the the object the method calls belong to. If you try, you'll get an IllegalMonitorStateException.
2.
You are required to synchronize on the same object that your wait()/notify()/notifyAll() calls belong to. For instance, your code will throw an IMSE as written. You'll want to call synchronized(this){ ... instead.

Guarded blocks -- notifyAll() vs interrupt()

This Q looks for verification and/or comments/opinions the following:
The example on Guarded Blocks is as follows:
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
The other end of this code-- the one setting joy properly is something like this:
public void setJoy2(TheClass t) {
synchronized (t) {
t.joy = true;
t.notifyAll();
}
}
The above does the "signaling" on joy by the use of notify().
An alternative is managing this "signalling" by interrupt():
public void guardedJoy2() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
synchronized(this) {
try {
wait();
} catch (InterruptedException e) {}
}
}
System.out.println("Joy and efficiency have been achieved!");
}
and the one setting joy and letting the thread waiting for it is:
public void setJoy2(TheClass t) {
t.joy = true;
t.interrupt();
}
I'm looking to make a comparison between the two-- setJoy() and setJoy2().
First of all, guardedJoy2() above can "hear" both setJoy() and setJoy2() properly-- can see when joy is set and act the way it is expected to(?)
How does guardedJoy2() compare to guardedJoy()?
It achieves does the same thing as guardedJoy()-- i might be missing something, but i'm not seeing a difference in the outcome. The only difference is that guardedJoy2() released the lock of this from within the loop, and someone else acquire it before the method terminates for some unexpected results. Setting that aside (i.e., assuming that this is the only place where the use of joy and its side effects appear in the code), there's not difference between guardedJoy() and guardedJoy2()(?)
guardedJoy2() responds to both setJoy() and setJoy2().
It can "hear" from setJoy() when it is done, re-acquires its lock and go from there.
And, it can "hear" from setJoy2()-- by receiving the interrupt and thus throwing InterruptedException to get out of wait(), that's also the end of synch'd statement, checks to see in while condition that joy is set and goes from there. If the interrupt was from "someone" else and not from the one setting joy, gets into the loop again the same way till joy is set.
When, wait() is invoked and thus the lock of this is released in guardedJoy2(),
some other thread can get in by acquiring this lock and do things that are not supposed to be done till joy is set and guardedJoy2() is supposed to return properly. However, setting this aside (again, assuming this isn't an issue-- the only thing being looked for is seeing that message on the last line of guardedJoy2() on the console.) This-- setJoy2() can be preferable in cases where other things can be done on the object while it's getting its joy set and go from there (in setJoy2(), the thread setting joy doesn't have to have the lock of the object to interrupt it while setJoy() should have that lock to invoke notifyAll() on it).
How does guardedJoy2() & setJoy2() compare to guardedJoy() & setJoy() above?
TIA.
I'm going of the assumption that you meant just notify() in your first setJoy rather than notifyAll().
First, it's important to note that if you're invoking interrupt() on an expression of type TheClass, then TheClass is a subclass of Thread. This goes against a number of -recommendations that state that you should use Runnable instances to encapsulate the logic to be run on a thread rather than subclassing the class Thread. The javadoc of Thread#join(int) also states
It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
This is because some implementations of Java use those methods to handle thread logic behind the scenes. If you do not know that implementation logic and use these methods with Thread instances, you might get undesired behavior.
Then, and this might warrant some profiling, throwing (creating) an exception is an expensive operation, probably more so than removing a Thread from an object's wait set. What's more, exceptions should be used for exceptional conditions, not to guide your application logic.
I was going to say that your second example's synchronization order may be incorrect (assuming joy was not volatile) because the read in the guardedJoy2 loop might not see the write in setJoy2. However, the Java Language Specification states
If thread T1 interrupts thread T2, the interrupt by T1
synchronizes-with any point where any other thread (including T2)
determines that T2 has been interrupted (by having an
InterruptedException thrown or by invoking Thread.interrupted or
Thread.isInterrupted)
So you still have visibility guarantees in place.

Does Java notify waiting threads implicitly?

I wrote a test app that should never stop. It issues t.wait() (t is a Thread object), but I never call notify. Why does this code end?
Despite the main thread synchronizing on t, the spawned thread runs, so it doesn't lock this object.
public class ThreadWait {
public static void main(String sArgs[]) throws InterruptedException {
System.out.println("hello");
Thread t = new MyThread();
synchronized (t) {
t.start();
Thread.sleep(5000);
t.wait();
java.lang.System.out.println("main done");
}
}
}
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
java.lang.System.out.println("" + i);
try {
Thread.sleep(500);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
The result is that the main thread waits 5 seconds and during this time worker gives its output. Then after 5 seconds are finished, the program exits. t.wait() does not wait. If the main thread wouldn't sleep for 5 seconds (commenting this line), then t.wait() would actually wait until the worker finishes. Of course, join() is a method to use here, but, unexpectedly, wait() does the same thing as join(). Why?
Maybe the JVM sees that, since only one thread is running, there is no chance to notify the main thread and solves the deadlock. If this is true, is it a documented feature?
I'm testing on Windows XP, Java 6.
You're waiting on a Thread - and while most objects aren't implicitly notified, a Thread object is notified when the thread terminates. It's documented somewhere (I'm looking for it...) that you should not use wait/notify on Thread objects, as that's done internally.
This is a good example of why it's best practice to use a "private" object for synchronization (and wait/notify) - something which only your code knows about. I usually use something like:
private final Object lock = new Object();
(In general, however, it's cleaner to use some of the higher-level abstractions provided by java.util.concurrent if you can. As noted in comments, it's also a good idea to implement Runnable rather than extending Thread yourself.)
The JavaDoc for wait gives the answer: spurious wakeups are possible. This means the JVM is free to end a call to wait whenever it wants.
The documentation even gives you a solution if you don't want this (which is probably always the case): put the call to wait in a loop and check whether the condition you wait for has become true after every wakeup.

Java - interrupting threads?

I got a question about interrupting threads in Java. Say I have a Runnable:
public MyRunnable implements Runnable {
public void run() {
operationOne();
operationTwo();
operationThree();
}
}
I want to implement something like this:
Thread t = new Thread(new MyRunnable());
t.run();
... // something happens
// we now want to stop Thread t
t.interrupt(); // MyRunnable receives an InterruptedException, right?
... // t is has now been terminated.
How can I implement this in Java? Specifically, how do I catch the InterruptedException in MyRunnable?
I recommend testing for Thread.isInterrupted(). Javadoc here. The idea here is that you are doing some work, most likely in a loop. On every iteration you should check if the interrupted flag is true and stop the work.
while(doingWork && !Thread.isInterrupted() {
// do the work
}
Edit: To be clear, your thread won't receive an InterruptedException if the sub tasks are not blocking or worst, eat that exception. Checking for the flag is the right method but not everybody follows it.
First, the 2nd line of your 2nd block of code should be t.start(), not t.run(). t.run() simply calls your run method in-line.
And yes, MyRunnable.run() must check periodically, while it is running, for Thread.currentThread().isInterrupted(). Since many things you might want to do in a Runnable involve InterruptedExceptions, my advice is to bite the bullet and live with them. Periodically call a utility function
public static void checkForInterrupt() throws InterruptedException {
if (Thread.currentThread().isInterrupted())
throw new InterruptedException();
}
EDIT added
Since I see a comment that the poster has no control over the individual operations, his MyRunnable.run() code should look like
public void run() {
operation1();
checkForInterrupt();
operation2();
checkForInterrupt();
operation3();
}
an InterruptedThreadException is only thrown when the thread is being blocked (wait, sleep, etc.) . Otherwise, you'll have to check Thread.currentThread().isInterrupted().
I think the answers above will pretty much fit your problem. I just want to add something on InterruptedException
Javadoc says:
InterruptedException :Thrown when a thread is waiting, sleeping, or
otherwise paused for a long time and another thread interrupts it
using the interrupt method in class Thread.
This means InterruptedException won't be thrown while running
operationOne();
operationTwo();
operationThree();
unless you are either sleeping, waiting for a lock or paused somewhere in these three methods.
EDIT If the provided code can not be changed as suggested by the nice and useful answers around here then I am afraid you have no way of interrupting your thread. As apposed to other languages such as C# where a thread can be aborted by calling Thread.Abort() Java does not have that possibility. See this link to know more about the exact reasons.
First of all, should be class in there
public class MyRunnable extends Thread {
public void run() {
if(!isInterrupted()){
operationOne();
operationTwo();
operationThree();
}
}
}
Would this work better?

Is Future.get() a replacement for Thread.join()?

I want to write a command line daemon that runs forever. I understand that if I want the JVM to be able to shutdown gracefully in linux, one needs to wrap the bootstrap via some C code. I think I'll be ok with a shutdown hook for now.
On to my questions:
My main(String[]) block will fire off a separate Superdaemon.
The Superdaemon will poll and loop forever.
So normally I would do:
class Superdaemon extends Thread { ... }
class Bootstrap
{
public static void main( String[] args )
{
Thread t = new Superdaemon();
t.start();
t.join();
}
}
Now I figured that if I started Superdaemon via an Executor, I can do
Future<?> f = exec.submit( new Superdaemon() );
f.get();
Is Future.get() implemented with Thread.join() ?
If not, does it behave equivalently ?
Regards,
ashitaka
Yes, the way you've written these is equivalent.
However, you don't really need to wait for the Superdaemon thread to complete. When the main thread finishes executing main(), that thread exits, but the JVM will not. The JVM will keep running until the last non-daemon thread exits its run method.
For example,
public class KeepRunning {
public static void main(String[] args) {
Superdaemon d = new Superdaemon();
d.start();
System.out.println(Thread.currentThread().getName() + ": leaving main()");
}
}
class Superdaemon extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + ": starting");
try { Thread.sleep(2000); } catch(InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + ": completing");
}
}
You'll see the output:
main: leaving main()
Thread-0: starting
Thread-0: completing
In other words, the main thread finishes first, then the secondary thread completes and the JVM exits.
The issue is that books like JCIP is advocating that we use Executors to starts Threads. So I'm trying my best not to use Thread.start(). I'm not sure if I would necessarily choose a particular way of doing things just based on simplicity. There must be a more convincing reason, no ?
The convincing reason to use java.util.concurrent is that multi-threaded programming is very tricky. Java offers the tools to that (Threads, the synchronized and volatile keywords), but that does not mean that you can safely use them directly without shooting yourself in the foot: Either too much synchronization, resulting in unnecessary bottlenecks and deadlocks, or too less, resulting in erratic behaviour due to race conditions).
With java.util.concurrent you get a set of utilities (written by experts) for the most common usage patterns, that you can just use without worrying that you got the low-level stuff right.
In your particular case, though, I do not quite see why you need a separate Thread at all, you might as well use the main one:
public static void main( String[] args )
{
Runnable t = new Superdaemon();
t.run();
}
Executors are meant for tasks that you want to run in the background (when you have multiple parallel tasks or when your current thread can continue to do something else).
Future.get() will get the future response from an asynchronous call. This will also block if the call has not been completed yet. It is much like a thread join.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Future.html
Sort'a. Future.get() is for having a thread go off and calculate something and then return it to the calling thread in a safe fashion. It'd work if the get never returned. But, I'd stick with the join call as it's simpler and no Executer overhead (not that there would be all that much).
Edit
It looks like ExecutorService.submit(Runnable) is intended to do exectly what you're attempting. It just returns null when the Runnable completes. Interesting.

Categories

Resources