我对一些相当简单的 Java 代码有一个奇怪的问题。
我有一个类LicenseManager
,它控制程序的许可,并且可以动态控制(可以按需发布新许可等)。LicenseManager
当然需要是线程安全的,因此,它使用了一个大锁。然而,它还有一个用于控制苹果的锁,我相信它在某种程度上涉及到这个死锁,但我真的不知道如何。该程序还安装了一个日志处理程序以支持企业日志功能。
只看代码LicenseManager
本身,我看不到一个问题。
import java.util.logging.*;
public class Main {
public static final LicenseManager licenseManager = new LicenseManager();
static class LicenseManager {
private static final Logger logger =
Logger.getLogger(LicenseManager.class.getName());
class InsufficientApplesException extends RuntimeException {};
class InsufficientPiesException extends RuntimeException {};
private int apples = 10;
private int pies = 10;
private boolean enterpriseLoggingEnabled = true;
// Apples have high contention; so they get their own lock.
private final Object appleLock = new Object();
void useApple() {
checkExpired();
synchronized (appleLock) {
logger.info("Using apple. Apples left: " + apples);
if (apples == 0) throw new InsufficientApplesException();
apples--;
}
}
/* Examples. There are lots of other operations like this
* on LicenseManager. We don't have time to prove that
* they are commutative, so we just use the main object lock
* around them all. The exception is when we find one with high
* contention, for example apples. */
synchronized void usePear() {checkExpired(); /*...*/}
synchronized void checkExpired() {}
synchronized void usePie() {
checkExpired();
logger.info("Using pie. Pies left: " + pies);
if (pies == 0) throw new InsufficientPiesException();
boolean reallyCanUsePie = true; // do expensive pie computation
if (reallyCanUsePie) {
useApple(); /* using a pie requires an apple.
* TODO: stop putting apples in the pumpkin pie */
pies--;
}
}
synchronized boolean isEnterpriseLoggingEnabled() {
return enterpriseLoggingEnabled;
}
}
public static void main(String[] args) {
// Install enterprise log handler on the root logger
Logger.getLogger("").addHandler(new Handler() {
@Override
public void publish(LogRecord lr) {
if (licenseManager.isEnterpriseLoggingEnabled())
System.out.println("ENTERPRISE ALERT! ["
+ lr.getLevel() + "] " + lr.getMessage());
}
@Override public void flush() {}
@Override public void close() throws SecurityException {}
});
// Simulate fat user
new Thread() {
@Override
public void run() {
while (true) {
licenseManager.usePie();
}
}
}.start();
// Simulate fat albeit healthy user
while (true) {
licenseManager.useApple();
}
}
}
当我运行它时:
$ java Main
Apr 25, 2013 3:23:19 PM Main$LicenseManager useApple
INFO: Using apple. Apples left: 10
Apr 25, 2013 3:23:19 PM Main$LicenseManager usePie
INFO: Using pie. Pies left: 10
ENTERPRISE ALERT! [INFO] Using pie. Pies left: 10
你会期望吃馅饼的人都死于馅饼用完,但两个线程都陷入僵局。
useApple
有趣的是,删除( )中的日志行logger.info("Using apple. Apples left: " + apples);
不会发生死锁(您不会看到日志中充斥着“using pie”,因为在任何 pie 可以使用之前,所有的苹果都碰巧消失了):
$ java Main
Exception in thread "main" Main$LicenseManager$InsufficientApplesException
at Main$LicenseManager.useApple(Main.java:24)
at Main.main(Main.java:79)
Apr 25, 2013 3:23:42 PM Main$LicenseManager usePie
INFO: Using pie. Pies left: 10
ENTERPRISE ALERT! [INFO] Using pie. Pies left: 10
Exception in thread "Thread-1" Main$LicenseManager$InsufficientApplesException
at Main$LicenseManager.useApple(Main.java:24)
at Main$LicenseManager.usePie(Main.java:43)
at Main$2.run(Main.java:72)
为什么?如何在不删除日志记录的情况下解决此问题?