Java find running thread

Get a list of all threads currently running in Java

Is there any way I can get a list of all running threads in the current JVM (including the threads not started by my class)? Is it also possible to get the Thread and Class objects of all threads in the list? I want to be able to do this through code.

13 Answers 13

Set threadSet = Thread.getAllStackTraces().keySet(); 

Performance: 0 ms for 12 threads (Azul JVM 16.0.1, Windows 10, Ryzen 5600X).

While much cleaner than the other alternative proposed, this has the downside of incurring the cost of getting stack traces for all threads. If you will be using those stack traces anyway, this is clearly superior. If not, then this may be significantly slower for no gain other than clean code.

@Eddie Is that an assumption from common sense, or did you do experiments? «significantly slower» you say; how much slower? Is it worth it? I question any attempt to make code worse for the sake of efficiency. If you have an efficiency requirement and an infrastructure to measure efficiency quantitatively, then I’m ok with people making code worse, because they seem to know what they’re doing. See the root of all evil according to Donald Knuth.

I haven’t timed these specific alternatives, but I’ve worked with other Java means of gathering stack traces vs just a list of threads. The performance impact seems to depend very strongly on which JVM you are using (JRockit vs Sun JVM for example). It’s worth measuring in your specific instance. Whether or not it will affect you depends on your JVM choice and on how many threads you have. I found that getting all stack traces via ThreadMXBean.dumpAllThreads for about 250 threads to take 150 — 200 msec while getting just the list of threads (without traces) to not be measurable (0 msec).

Читайте также:  Создание приложений для windows java

On my system (Oracle Java 1.7 VM), a quick check shows that this method is ~70..80 times SLOWER than the alternative below. Stack traces and reflection belong to the heaviest Java operations.

@thejoshwolfe: Of course, readability is an important factor, and one should not micro-optimize etc. However, I did my research while writing a small application performance monitor. For this kind of tool, a minimal performance imprint is essential to get reliable data, so I chose the stacktrace-less method.

Источник

How to check if an Android Thread is running

Is there a way to check if a Thread object has had start called on it already? I’m trying to so something like:

4 Answers 4

Assuming that rt is a Thread , just check rt.isAlive() .

Alternatively, just use a boolean flag and set it to true right before you start your thread.

I would actually prefer the boolean approach so there is no way that the main thread could start the other thread twice — there may be a short delay until your Thread is up and running, and if your main thread tries to start the thread twice in quick succession, it may get a «false» negative on rt.isAlive() .

isAlive keeps returning false for me somehow(I just updated my answer to reflect my code.) Using the boolean should work though as I’m already using one to stop my internal Thread loop. Thanks for the help!

Yeah that worked. Basically I don’t initialize the Thread until the action is hit, then I check my internal thread bool after that.

Glad to hear it worked! The only thing I want to reiterate is that you need to be aware of the delay between starting a thread and having it run — if you set a bool in your Thread’s run method, there’s a short period of time where you started the thread, but the bool isn’t set to true yet. That’s why I recommend setting it in the main thread.

EboMike: are you actually seeing isAlive() returning false? Starting in Eclair, the isAlive() function just returns «vmThread != null», and the vmThread field is set by the VM before pthread_create is called. If the main thread calls start(), any subsequent isAlive() call from the main thread will return true. Thread creation is not asynchronous. (In donut and earlier, isAlive() worked differently, but should still be reliably returning «true» after calling create().)

It’s fadden! Long time no see! I’ve never used isAlive() myself, I just waded through the documentation and it seemed like something that would do the trick here. Btw — good to know about thread synchronization not being asynchronous (although, to be fair, it is presumably still not defined how long it will take until the first instruction of the thread’s run() method is executed).

I’ve used this approach with success:

if ( mythread.getState() == Thead.State.NEW ) //then we have a brand new thread not started yet, lets start it mythread.start(); else //it is running already compensate 

If you called start on it, and it is running, you will get an IllegalThreadStateException . Catching that is one way to know.

Another option is to extend Thread and add a boolean where you keep track of whether or not your Thread has been started. You can override the start method of Thread to check the boolean before calling up to super.start() .

You should be very careful when using threads in Android though. Make sure you understand the lifecycle of the component that is starting it. Also, you should consider some of the helper classes like Handler and AsyncTask instead of directly spawning threads.

Источник

How to find a Java thread running on Linux with ps -axl?

I have a running JVM with two threads. Is it possible to see these running threads on my Linux OS with ps -axl ? I am trying to find out what priority the OS is giving to my threads. More info about this other issue here.

8 Answers 8

for finding your java process. Sample Output:

3825 RemoteMavenServer -Djava.awt.headless=true -Xmx512m -Dfile.encoding=MacRoman 6172 AppMain -Didea.launcher.port=7533 -Didea.launcher.bin.path=/Applications/IntelliJ IDEA 10.app/bin -Dfile.encoding=UTF-8 6175 Jps -Dapplication.home=/Library/Java/JavaVirtualMachines/1.6.0_31-b04-411.jdk/Contents/Home -Xms8m 

(6172 is id of your process) to get stack of threads inside jvm. Thread priority could be found from it. Sample output:

. "main" **prio=5** tid=7ff255800800 nid=0x104bec000 waiting on condition [104beb000] java.lang.Thread.State: TIMED_WAITING (sleeping) at java.lang.Thread.sleep(Native Method) at au.com.byr.Sample.main(Sample.java:11) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) . 

EDIT: If application running under different user than yourself (typical case on production and other non-local environments) then jps/jstack should be run via sudo. Examples:

sudo jps -v sudo jstack 6172 

Источник

How to find and stop all currently running threads?

I have an multiple-threaded java project and I want to add a method stop() to stop all the running threads. The problem is that this project is developed by someone else, and I am not familiar with how it implements multiple threads. What I know is that once the project get started, many threads are invoked and they run forever. Is there a way to find all running threads and stop them? I have searched a lot, and found how to get a list of running threads:

Set threadSet = Thread.getAllStackTraces().keySet(); 

What to do next to stop all the running threads? The reason why I want to stop these threads is that I need to deploy this project to OSGi container as a bundle. Once the bundle is started, multiple threads run forever. So I need to implement a destroy() method to stop all threads to control the bundle lifecycle. How about

for (Thread t : Thread.getAllStackTraces().keySet()) < if (t.getState()==Thread.State.RUNNABLE) t.interrupt(); >for (Thread t : Thread.getAllStackTraces().keySet())

why do you want to stop all threads? If you all looking to stop your application then System.exit is the right choice.

Don’t try to stop all threads. There’s a reason why the stop() of Thread has been deprecated. Have a look at the documentation: docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#stop()

@Ankit Because I need to deploy this project to OSGi container as a bundle. Once the bundle is started, multiple threads run forever. So I need to implement a destroy() method to stop all threads to control the bundle lifecycle.

can’t you use OSGi bundle stop method itself. I don’t know much about OSGi, ignore my comment if not that useful.

3 Answers 3

This is a dangerous idea. The Javadoc for Thread.stop() explains:

This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait.

Fundamentally, threads need to be built and designed to safely terminate, it is not possible to safely kill arbitrary threads. A fairly standard pattern is implemented like so:

public abstract class StoppableRunnable implements Runnable < private volatile boolean stopWork; private boolean done; public final void run() < setup(); while(!stopWork && !done) < doUnitOfWork(); >cleanup(); > /** * Safely instructs this thread to stop working, * letting it finish it's current unit of work, * then doing any necessary cleanup and terminating * the thread. Notice that this does not guarentee * the thread will stop, as doUnitOfWork() could * block if not properly implemented. */ public void stop() < stopWork = true; >protected void done() < done = true; >protected void setup() < >protected void cleanup() < >/** * Does as small a unit of work as can be defined * for this thread. Once there is no more work to * be done, done() should be called. */ protected abstract void doUnitOfWork(); > 

You implied you aren’t the author of these threads, which suggest they may not be safely stoppable. In such a case, you can call Thread.interrupt() to instruct the thread to stop what it’s doing (instead of the pattern described above, you could use Thread.interrupt() to similar effect) however similarly, if the thread’s designer hasn’t written it to handle interrupts, this may not do anything or cause inconsistent states or other errors.

Ultimately, Thread.stop() is what you want if you just want to «[Force] the thread to stop executing» and can’t modify the thread’s implementation; however like using kill in Unix, this is a dangerous proposition, and you should essentially consider your JVM to be in an unstable and irreparable state after terminating a thread in this way, and attempt to exit the program as quickly as possible thereafter.

Regarding your suggestion of interrupting then stopping:

There’s still a lot of problems here, in particular, interrupting does not guarantee the thread will interrupt immediately (it works similarly, though less explicitly, to my StoppableRunnable above) and instead sets a flag that the thread should interrupt when possible. This means you could call Thread.interrupt() , the thread could start it’s proper interrupt-handling behavior, then midway through that, your call to Thread.stop() fires, violently killing the thread and potentially breaking your JVM. Calls to Thread.interrupt() provide no guarantee as to when or how the thread will respond to that interrupt, which is why I prefer the explicit behavior in StoppableRunnable . Needless to say, if you’re ever going to call Thread.stop() there’s little to be gained by calling Thread.interrupt() first. I don’t recommend it, but you might as well just call Thread.stop() in the first place.

Additionally, recognize that the code running your loop is itself in a thread — meaning your loop could very well kill itself first, leaving all other threads running.

Источник

Оцените статью