|
1
|
|
|
package de.pewpewproject.lasertag.common.util; |
|
2
|
|
|
|
|
3
|
|
|
import com.google.common.util.concurrent.ThreadFactoryBuilder; |
|
4
|
|
|
|
|
5
|
|
|
import java.util.concurrent.ExecutorService; |
|
6
|
|
|
import java.util.concurrent.Executors; |
|
7
|
|
|
import java.util.concurrent.ScheduledExecutorService; |
|
8
|
|
|
import java.util.concurrent.TimeUnit; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Class with utility methods for working with threads |
|
12
|
|
|
* |
|
13
|
|
|
* @author Étienne Muser |
|
14
|
|
|
*/ |
|
15
|
|
|
public class ThreadUtil { |
|
16
|
|
|
/** |
|
17
|
|
|
* Correctly shuts down a executor service with timeout = 3 seconds |
|
18
|
|
|
* <p> |
|
19
|
|
|
* ALWAYS DO THIS AS THE LAST OPERATION! This method blocks for 3 seconds! |
|
20
|
|
|
* Do everything you need to do before calling this method! |
|
21
|
|
|
* @param service The executor service to shut down |
|
22
|
|
|
*/ |
|
23
|
|
|
public static void attemptShutdown(ExecutorService service) { |
|
24
|
|
|
attemptShutdown(service, 3L); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Correctly shuts down a executor service |
|
29
|
|
|
* <p> |
|
30
|
|
|
* ALWAYS DO THIS AS THE LAST OPERATION! This method blocks for <code>timeout</code> seconds! |
|
31
|
|
|
* Do everything you need to do before calling this method! |
|
32
|
|
|
* @param service The executor service to shut down |
|
33
|
|
|
* @param timeout The timeout in seconds to use when waiting for termination |
|
34
|
|
|
*/ |
|
35
|
|
|
public static void attemptShutdown(ExecutorService service, long timeout) { |
|
36
|
|
|
service.shutdown(); |
|
37
|
|
|
|
|
38
|
|
|
boolean successful; |
|
39
|
|
|
try { |
|
40
|
|
|
successful = service.awaitTermination(timeout, TimeUnit.SECONDS); |
|
41
|
|
|
} catch (InterruptedException var3) { |
|
42
|
|
|
successful = false; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
if (!successful) { |
|
46
|
|
|
service.shutdownNow(); |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Create a scheduled executor service with the given format as the name specifier for the threads |
|
52
|
|
|
* @param format The name format for the created threads |
|
53
|
|
|
* @return |
|
54
|
|
|
*/ |
|
55
|
|
|
public static ScheduledExecutorService createScheduledExecutor(String format) { |
|
56
|
|
|
return Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat(format).setDaemon(true).build()); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|