私有静态内部类


最近在看开源的一个组件zookeeper的源代码,在自己做实验,调用zookeeper接口实现分布式锁的时候,看到了一个类,是private static的,由此引发了我的思考,为啥这个类要这么设计?联想到之前看到的一些开源组件或者JDK的源码,也看到了类似的private static的设计,所以就上网搜索了一番。

特点

1 防止外部类直接调用或者实例化。

2 减少对象的数量。

3 延迟加载

PS: private的含义比较明确,目的也很明确,就是不想让别的类用。关键在于static的含义。

先看源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private boolean internalLock(long time, TimeUnit unit) throws Exception {
Thread currentThread = Thread.currentThread();
InterProcessMutex.LockData lockData = (InterProcessMutex.LockData)this.threadData.get(currentThread);
if (lockData != null) {
lockData.lockCount.incrementAndGet();
return true;
} else {
String lockPath = this.internals.attemptLock(time, unit, this.getLockNodeBytes());
if (lockPath != null) {
InterProcessMutex.LockData newLockData = new InterProcessMutex.LockData(currentThread, lockPath);
this.threadData.put(currentThread, newLockData);
return true;
} else {
return false;
}
}
}

private static class LockData {
final Thread owningThread;
final String lockPath;
final AtomicInteger lockCount;

private LockData(Thread owningThread, String lockPath) {
this.lockCount = new AtomicInteger(1);
this.owningThread = owningThread;
this.lockPath = lockPath;
}
}

这个类 LockData,是独占锁的锁内容,具体含义不表。外部类是InterProcessMutex,一说是因为LockData如果不是static的,就会持有外部类InterProcessMutex的引用,容易造成内存泄漏。

再看源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];

static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);

// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}

private IntegerCache() {}
}

这里是jdk的源码,是int的内部缓存。

接下来再思考吧。