From: Eric Sosman on
On 12/14/2009 12:22 PM, Lothar Kimmeringer wrote:
> Eric Sosman wrote:
> [...]
>> If the victim thread isn't cooperating (by checking a
>> "stop now" flag occasionally or some such), the only way I
>> can think of to stop it safely is System.exit().
>
> System.exit waits for all non-daemon-threads to stop.
> So if the Thread you want to kill is not a daemon-thread
> and it ignores all attempts to stop, you're screwed.

Are you sure? The Javadoc for System and for Runtime
don't mention any such thing. There's lots about shutdown
hooks and finalizers and recursive calls to exit(), but
nothing about waiting for other threads.

Hmmm: If you're right, this program will never terminate:

public class RunForever implements Runnable {

public static void main(String[] unused) {
demonic();
new Thread(new RunForever()).start();
stall(3500);
System.exit(0);
}

public void run() {
demonic();
for (;;) {
stall(1000);
}
}

private static void demonic() {
Thread self = Thread.currentThread();
System.err.println(self.getName()
+ (self.isDaemon() ? " is " : " is not ")
+ "a daemon");
}

private static void stall(long time) {
String name = Thread.currentThread().getName();
try {
Thread.sleep(time);
System.err.println(name
+ " awoke at " + System.currentTimeMillis());
} catch (InterruptedException ex) {
System.err.println(name
+ " interrupted at " + System.currentTimeMillis());
}
}
}

On my machine, it terminates as expected. Bug in my Java?

--
Eric Sosman
esosman(a)ieee-dot-org.invalid
From: Roedy Green on
On Mon, 14 Dec 2009 01:05:17 -0800 (PST), john
<junzhang1983(a)gmail.com> wrote, quoted or indirectly quoted someone
who said :

>in my project, sometimes some java thread can't be killed immediately,
>is there any good ways to slove the problem?
>in java API Thread.java, there isn't stop method, whether it means in
>java, App writer can't kill a thread forcely or there is some around
>methods?

The only safe way to do it is to have the thread check a boolean
periodically and commit suicide if true.

--
Roedy Green Canadian Mind Products
http://mindprod.com
The future has already happened, it just isn�t evenly distributed.
~ William Gibson (born: 1948-03-17 age: 61)