[45] | 1 | package geniusweb.partiesserver.websocket;
|
---|
| 2 |
|
---|
| 3 | import java.util.LinkedList;
|
---|
| 4 | import java.util.List;
|
---|
| 5 | import java.util.logging.Level;
|
---|
| 6 |
|
---|
| 7 | import tudelft.utilities.logging.Reporter;
|
---|
| 8 |
|
---|
| 9 | /**
|
---|
| 10 | * Keeps track of threads active for a PartySocket. Needed so that we can kill
|
---|
| 11 | * all relevant threads when it comes to forced termination.
|
---|
| 12 | */
|
---|
| 13 | public class ActiveThreads {
|
---|
| 14 | private final List<Thread> threads = new LinkedList<>();
|
---|
| 15 | private final Reporter log;
|
---|
| 16 |
|
---|
| 17 | public ActiveThreads(Reporter log) {
|
---|
| 18 | this.log = log;
|
---|
| 19 | }
|
---|
| 20 |
|
---|
| 21 | /**
|
---|
| 22 | * Add the current thread as active thread
|
---|
| 23 | */
|
---|
| 24 | public synchronized void add() {
|
---|
| 25 | threads.add(Thread.currentThread());
|
---|
| 26 | }
|
---|
| 27 |
|
---|
| 28 | /**
|
---|
| 29 | * Remove the current thread as active thread. To be called when thread
|
---|
| 30 | * finished nicely.
|
---|
| 31 | */
|
---|
| 32 | public synchronized void remove() {
|
---|
| 33 | threads.remove(Thread.currentThread());
|
---|
| 34 |
|
---|
| 35 | }
|
---|
| 36 |
|
---|
| 37 | /**
|
---|
| 38 | *
|
---|
| 39 | * @return true if no threads currently running.
|
---|
| 40 | */
|
---|
| 41 | public synchronized boolean isEmpty() {
|
---|
| 42 | return threads.isEmpty();
|
---|
| 43 | }
|
---|
| 44 |
|
---|
| 45 | @SuppressWarnings("deprecation")
|
---|
| 46 | public synchronized void killall() {
|
---|
| 47 |
|
---|
| 48 | /*
|
---|
| 49 | * The method stop(Throwable) does not work anymore. we need to call
|
---|
| 50 | * stop() which will result in nonsense stacktrace pointing to US
|
---|
| 51 | * instead of the real problem. Only solution is to print stacktrace
|
---|
| 52 | * ourselves.
|
---|
| 53 | */
|
---|
| 54 | for (Thread thread : threads) {
|
---|
| 55 | String stacktrace = "";
|
---|
| 56 | for (StackTraceElement element : thread.getStackTrace()) {
|
---|
| 57 | stacktrace += "\t" + element.toString() + "\n";
|
---|
| 58 | }
|
---|
| 59 |
|
---|
| 60 | /* the most powerful kill, deprecated but required here. */
|
---|
| 61 | try {
|
---|
| 62 | thread.stop();
|
---|
| 63 | log.log(Level.INFO,
|
---|
| 64 | "Killed thread with stack trace\n" + stacktrace);
|
---|
| 65 | } catch (ThreadDeath e) {
|
---|
| 66 | log.log(Level.INFO, "Noticed thread already was stopped.");
|
---|
| 67 | }
|
---|
| 68 | }
|
---|
| 69 | threads.clear();
|
---|
| 70 | }
|
---|
| 71 | }
|
---|