简体   繁体   中英

How to think about Java Threads? aka Thread.stop

Exposition:

I think the Java VM is awesome. It's guarantee of the safety of bytecode, the the standard libraries, ... are amazing, especially the ability to load a Java class on the fly, and know that it can't crash the VM (good luck with *.so files or kernel modules).

One thing I don't understand, is how Java treats Thread.stop

I've read http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html but it seems weird for the following reasons:

1) Resource Management

On Unix OS, if a process is hogging up resources, I can kill -9 it.

2) Breaking of Abstraction:

If I start a computationally expensive job, and I no longer need the computation, I can kill -9 it. Under this Java threading model, my computation thread has to periodically check for some boolean flag to see whether it should quit [this seems like breaking abstraction layers -- when I'm writing computation code, I should focus on computation code, not where to spread out checks for whether it should terminate.

3) Safety of Lock/Monitors

So the official reason is "what is a thread is holding a Lock/Monitor and it gets Thread.stopped ? The objects will be left in damaged states" -- yet, in OSes this is not a problem, we have interrupt handlers. Why can't Java threads have interrupt handlers that work like OS interrupt handlers?

Question:

Clearly, I am thinking about Java Threads with the wrong mental model. How should I be thinking about Java threads?

Thanks!

I think the key thing to remember is that threads are not processes. The only thing that threads "own" is the execution thread, since everything else can potentially be shared with other threads within the same process (memory space). Stopping a thread can't clean anything up because things may still be completely valid for other threads to handle.

In an operating system process, the OS keeps track of everything that the process owns (memory, files, locks, etc) and cleans things up properly when you SIGKILL a process.

You seems to be confusing threads and processes.

Resources(Allocated memory, Locks, file handles and so on) belong to the process not to any specific thread in the process. The entire point(And danger) of threads is that multiple threads within the same process share resources.

So it does not sense to talk about any resource belonging to a single thread.

ps: I am pretty sure you can't use kill/kill -9 to kill a thread in Linux. The man page for kill say it can only kill a process or process groups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM