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
36
37
38 private static final Logger LOGGER = LogManager.getRootLogger();
39
40
41
42
43
44
45 private final Map<AbstractElementDatabase, AbstractSuspendable> suspendables = new ConcurrentHashMap<>(new HashMap<>());
46
47 private final InjectionModel injectionModel;
48
49 public ThreadUtil(InjectionModel injectionModel) {
50 this.injectionModel = injectionModel;
51 }
52
53
54
55
56
57
58
59 public void put(AbstractElementDatabase elementDatabase, AbstractSuspendable suspendable) {
60 this.suspendables.put(elementDatabase, suspendable);
61 }
62
63
64
65
66
67
68
69
70 public AbstractSuspendable get(AbstractElementDatabase elementDatabase) {
71 return this.suspendables.get(elementDatabase);
72 }
73
74
75
76
77
78
79 public void remove(AbstractElementDatabase elementDatabase) {
80 this.suspendables.remove(elementDatabase);
81 }
82
83
84
85
86
87 public void reset() {
88 this.suspendables.values().forEach(AbstractSuspendable::stop);
89 this.suspendables.clear();
90 }
91
92 public ExecutorService getExecutor(String nameThread) {
93 ExecutorService taskExecutor;
94
95 if (this.injectionModel.getMediatorUtils().getPreferencesUtil().isLimitingThreads()) {
96 int countThreads = this.injectionModel.getMediatorUtils().getPreferencesUtil().countLimitingThreads();
97 taskExecutor = Executors.newFixedThreadPool(countThreads, new ThreadFactoryCallable(nameThread));
98 } else {
99 taskExecutor = Executors.newCachedThreadPool(new ThreadFactoryCallable(nameThread));
100 }
101 return taskExecutor;
102 }
103
104 public void shutdown(ExecutorService taskExecutor) {
105 int timeout = 15;
106 if (this.injectionModel.getMediatorUtils().getPreferencesUtil().isConnectionTimeout()) {
107 timeout = this.injectionModel.getMediatorUtils().getPreferencesUtil().countConnectionTimeout();
108 }
109
110 try {
111 taskExecutor.shutdown();
112 if (!taskExecutor.awaitTermination(timeout, TimeUnit.SECONDS)) {
113 taskExecutor.shutdownNow();
114 }
115 } catch (InterruptedException e) {
116 LOGGER.log(LogLevelUtil.IGNORE, e, e);
117 Thread.currentThread().interrupt();
118 }
119 }
120 }