JavaRush/Java Blog/Random EN/How to get a list of dead threads from a ThreadGroup? lev...
Dead_MOPO3
Level 36

How to get a list of dead threads from a ThreadGroup? level 28

Published in the Random EN group
members
Well, actually, the question itself is in the title. Who figured it out, tell me. I found this option, but I don’t like it at all and it doesn’t work) public static void main(String[] args) { /* * For testing purposes */ ThreadGroup tg = new ThreadGroup( "MyThreadGroup" ); Thread subThread = new Thread( tg, "New Thread - Inactive" ); try { /* * GETTING THREADS - PROBABLY BETTER TO GET IT BY USING * getDeclaredFields() AND LOOPING TILL GET ONE OF TYPE * Thread[] SINCE A FUTURE VERSION MIGHT CHANGE THE NAME * BUT SINCE IS PACKAGE-LEVEL ACCESS, IT'S PROBABLY USED * ELSEWHERE IN THE PACKAGE, AND THIS IS JUST AN EXAMPLE */ Field field = tg.getClass().getDeclaredField( "threads" ); //NEED TO SUPPRESS ACCESS CHECKS field.setAccessible( true ); //EVEN IF SECURITY IS OFF YOU NEED THIS!!!! Thread[] tgThreads = ( Thread[] ) field.get( tg ); for ( int i = 0; i < tgThreads.length; i++ ) { if ( tgThreads[ i ] != null ) System.out.println( tgThreads[ i ].getName() + " = " + tgThreads[ i ].isAlive() ); } } catch (NoSuchFieldException nsfe) { nsfe.printStackTrace(); } catch (IllegalAccessException iae) { iae.printStackTrace(); } } It turns out that the line Thread[] tgThreads = ( Thread[] ) field.get( tg ); does not generate an array for me. I read that it seems like you can somehow go into System.SecurityManager and set ReflectPermission("suppressAccessChecks"). but the approach is too hardcoded. get to private fields through reflection...
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet