package geniusweb.partiesserver.websocket; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import tudelft.utilities.logging.Reporter; /** * Keeps track of threads active for a PartySocket. Needed so that we can kill * all relevant threads when it comes to forced termination. */ public class ActiveThreads { private final List threads = new LinkedList<>(); private final Reporter log; public ActiveThreads(Reporter log) { this.log = log; } /** * Add the current thread as active thread */ public synchronized void add() { threads.add(Thread.currentThread()); } /** * Remove the current thread as active thread. To be called when thread * finished nicely. */ public synchronized void remove() { threads.remove(Thread.currentThread()); } /** * * @return true if no threads currently running. */ public synchronized boolean isEmpty() { return threads.isEmpty(); } @SuppressWarnings("deprecation") public synchronized void killall() { /* * The method stop(Throwable) does not work anymore. we need to call * stop() which will result in nonsense stacktrace pointing to US * instead of the real problem. Only solution is to print stacktrace * ourselves. */ for (Thread thread : threads) { String stacktrace = ""; for (StackTraceElement element : thread.getStackTrace()) { stacktrace += "\t" + element.toString() + "\n"; } /* the most powerful kill, deprecated but required here. */ try { thread.stop(); log.log(Level.INFO, "Killed thread with stack trace\n" + stacktrace); } catch (ThreadDeath e) { log.log(Level.INFO, "Noticed thread already was stopped."); } } threads.clear(); } }