我有一个类Singleton
(为这个例子简化)
public class Singleton {
private final static Lock METHOD_1_LOCK = new ReentrantLock();
private final static Lock METHOD_2_LOCK = new ReentrantLock();
static {
try {
init();
}catch(InterruptedException ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static void init() throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(() -> {
method1();
});
executorService.submit(() -> {
method2();
});
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
}
public static List<String> method1() {
METHOD_1_LOCK.lock();
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1");
return Stream.of("b").collect(Collectors.toList());
}finally {
METHOD_1_LOCK.unlock();
}
}
public static List<String> method2() {
METHOD_2_LOCK.lock();
try {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2");
return Stream.of("a").collect(Collectors.toList());
}finally {
METHOD_2_LOCK.unlock();
}
}
private Singleton() {
}
}
Class.forName
我想通过调用一个单独的线程来预初始化:
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Class.forName(Singleton.class.getName());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
// working alternative:
// try {
// Singleton.init();
// }catch(InterruptedException ex) {
// ex.printStackTrace();
// }
});
thread.start();
thread.join();
}
这个构造永远不会从ExecutorService.awaitTermination
.
如果我通过注释(并注释掉另一个)切换到标记为“工作替代”的代码并注释掉代码中的static
块,则按Singleton
预期执行(method1
并method2
根据输出以相反的顺序调用和返回)。
由于“工作替代方案”可以防止问题并且我可以忍受它,我正在寻找这种行为的解释。
我的意图是使用Class.forName
而不是Singleton.init
能够添加更多静态初始化任务,Singleton
而无需考虑它们是否被预初始化例程覆盖。我同意整个设置并不理想。