Skip to content

Commit

Permalink
Add shutdown hook for JetCacheExecutor, use DiscardPolicy for executo…
Browse files Browse the repository at this point in the history
…rs in JetCacheExecutor.
  • Loading branch information
areyouok committed Jun 2, 2019
1 parent c29568c commit 8796895
Showing 1 changed file with 23 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.alicp.jetcache.support;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.*;

/**
* Created on 2017/5/3.
Expand All @@ -14,35 +13,51 @@ public class JetCacheExecutor {

private static int threadCount;

@SuppressWarnings("PMD.ThreadPoolCreationRule")
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
if (defaultExecutor != null) {
defaultExecutor.shutdownNow();
}
if (heavyIOExecutor != null) {
heavyIOExecutor.shutdownNow();
}
}
});
}

public static ScheduledExecutorService defaultExecutor() {
if (defaultExecutor != null) {
return defaultExecutor;
}
synchronized (JetCacheExecutor.class) {
if (defaultExecutor == null) {
defaultExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
ThreadFactory tf = r -> {
Thread t = new Thread(r, "JetCacheDefaultExecutor");
t.setDaemon(true);
return t;
});
};
defaultExecutor = new ScheduledThreadPoolExecutor(
1, tf, new ThreadPoolExecutor.DiscardPolicy());
}
}
return defaultExecutor;
}

@SuppressWarnings("PMD.ThreadPoolCreationRule")
public static ScheduledExecutorService heavyIOExecutor() {
if (heavyIOExecutor != null) {
return heavyIOExecutor;
}
synchronized (JetCacheExecutor.class) {
if (heavyIOExecutor == null) {
heavyIOExecutor = Executors.newScheduledThreadPool(10, r -> {
ThreadFactory tf = r -> {
Thread t = new Thread(r, "JetCacheHeavyIOExecutor" + threadCount++);
t.setDaemon(true);
return t;
});
};
heavyIOExecutor = new ScheduledThreadPoolExecutor(
10, tf, new ThreadPoolExecutor.DiscardPolicy());
}
}
return heavyIOExecutor;
Expand Down

0 comments on commit 8796895

Please sign in to comment.