33import java .util .concurrent .Executors ;
44import java .util .concurrent .ScheduledExecutorService ;
55import java .util .concurrent .ThreadFactory ;
6+ import java .util .concurrent .locks .Lock ;
7+ import java .util .concurrent .locks .ReentrantLock ;
68
7- @ SuppressWarnings ("PMD.DoNotUseThreads" )
9+ @ SuppressWarnings ({
10+ "PMD.DoNotUseThreads" ,
11+ "PMD.SingleMethodSingleton" ,
12+ "PMD.NonThreadSafeSingleton"
13+ })
814public final class ScheduleExecutorSingleton {
9- // Pool size for the thread pool
10- private static final int POOL_SIZE = 1 ;
15+ // Default pool size for the thread pool
16+ private static final int DEFAULT_POOL_SIZE = 1 ;
17+ private static ScheduleExecutorSingleton instance ;
18+ private static final Lock LOCK = new ReentrantLock ();
1119 private final ScheduledExecutorService scheduler ;
1220
21+ /** Default constructor which takes the default pool size */
1322 private ScheduleExecutorSingleton () {
23+ this (DEFAULT_POOL_SIZE );
24+ }
25+
26+ /**
27+ * Constructor to set a different pool size
28+ *
29+ * @param poolSize
30+ */
31+ private ScheduleExecutorSingleton (int poolSize ) {
1432 // Use Daemon threads to prevent that the user need to call shutdown
1533 // even if its program was already terminated
1634 ThreadFactory daemonThreadFactory =
@@ -19,20 +37,28 @@ private ScheduleExecutorSingleton() {
1937 thread .setDaemon (true );
2038 return thread ;
2139 };
22- scheduler = Executors .newScheduledThreadPool (POOL_SIZE , daemonThreadFactory );
40+ this . scheduler = Executors .newScheduledThreadPool (poolSize , daemonThreadFactory );
2341 }
2442
25- public ScheduledExecutorService getScheduler () {
26- return scheduler ;
43+ public static ScheduleExecutorSingleton getInstance () {
44+ return getInstance ( DEFAULT_POOL_SIZE ) ;
2745 }
2846
29- // In order to make the Linter happy this is the only solution which is accepted.
30- // Lock/ReentrantLock, synchronized and volatile are in general not accepted.
31- private static final class SingletonHolder {
32- public static final ScheduleExecutorSingleton INSTANCE = new ScheduleExecutorSingleton ();
47+ public static ScheduleExecutorSingleton getInstance (int poolSize ) {
48+ if (instance == null ) {
49+ LOCK .lock ();
50+ try {
51+ if (instance == null ) {
52+ instance = new ScheduleExecutorSingleton (poolSize );
53+ }
54+ } finally {
55+ LOCK .unlock ();
56+ }
57+ }
58+ return instance ;
3359 }
3460
35- public static ScheduleExecutorSingleton getInstance () {
36- return SingletonHolder . INSTANCE ;
61+ public ScheduledExecutorService getScheduler () {
62+ return scheduler ;
3763 }
3864}
0 commit comments