1
2
3
4
5
6
7
8
9
10
11 package com.jsql.util;
12
13 import com.jsql.model.InjectionModel;
14 import com.jsql.model.bean.database.AbstractElementDatabase;
15 import com.jsql.model.suspendable.AbstractSuspendable;
16 import com.jsql.model.suspendable.callable.ThreadFactoryCallable;
17 import org.apache.logging.log4j.LogManager;
18 import org.apache.logging.log4j.Logger;
19
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ExecutorService;
24 import java.util.concurrent.Executors;
25 import java.util.concurrent.TimeUnit;
26
27
28
29
30
31
32
33 public final class ThreadUtil {
34
35 private static final Logger LOGGER = LogManager.getRootLogger();
36
37
38
39
40
41
42 private final Map<AbstractElementDatabase, AbstractSuspendable> suspendables = new ConcurrentHashMap<>(new HashMap<>());
43
44 private final InjectionModel injectionModel;
45
46 public ThreadUtil(InjectionModel injectionModel) {
47 this.injectionModel = injectionModel;
48 }
49
50
51
52
53
54
55
56 public void put(AbstractElementDatabase elementDatabase, AbstractSuspendable suspendable) {
57 this.suspendables.put(elementDatabase, suspendable);
58 }
59
60
61
62
63
64
65
66
67 public AbstractSuspendable get(AbstractElementDatabase elementDatabase) {
68 return this.suspendables.get(elementDatabase);
69 }
70
71
72
73
74
75
76 public void remove(AbstractElementDatabase elementDatabase) {
77 this.suspendables.remove(elementDatabase);
78 }
79
80
81
82
83
84 public void reset() {
85 this.suspendables.values().forEach(AbstractSuspendable::stop);
86 this.suspendables.clear();
87 }
88
89 public ExecutorService getExecutor(String nameThread) {
90 ExecutorService taskExecutor;
91 if (this.injectionModel.getMediatorUtils().preferencesUtil().isLimitingThreads()) {
92 int countThreads = this.injectionModel.getMediatorUtils().preferencesUtil().countLimitingThreads();
93 taskExecutor = Executors.newFixedThreadPool(countThreads, new ThreadFactoryCallable(nameThread));
94 } else {
95 taskExecutor = Executors.newCachedThreadPool(new ThreadFactoryCallable(nameThread));
96 }
97 return taskExecutor;
98 }
99
100 public void shutdown(ExecutorService taskExecutor) {
101 int timeout = 15;
102 if (this.injectionModel.getMediatorUtils().preferencesUtil().isConnectionTimeout()) {
103 timeout = this.injectionModel.getMediatorUtils().preferencesUtil().countConnectionTimeout();
104 }
105 try {
106 taskExecutor.shutdown();
107 if (!taskExecutor.awaitTermination(timeout, TimeUnit.SECONDS)) {
108 taskExecutor.shutdownNow();
109 }
110 } catch (InterruptedException e) {
111 LOGGER.log(LogLevelUtil.IGNORE, e, e);
112 Thread.currentThread().interrupt();
113 }
114 }
115 }