源码中涉及以下知识点:
1.java.security.MessageDigest
2.org.apache.lucene.store.LockFactory
org.apache.lucene.store.FSLockFactory
见FSDirectory构造
3.32bit与64bit操作系统
4.sync中RandomAccessFile、FileDescriptor
5.getLockId中位运算
相比父类Directory
新增方法1:static open()
因为SUN的JRE长期在WIN平台上存在问题,所以使用NIOFSDirectory性能会较差,这样需要根据不同平台来选择合理的
FSDirectory,静态方法open提供了一种简化的方法来创建平台合适的FSDirectory实例,免除了开发者自己进行平台判断。
public static FSDirectory open(File path) throws IOException { return open(path, null); } public static FSDirectory open(File path, LockFactory lockFactory) throws IOException { if (Constants.WINDOWS) { return new SimpleFSDirectory(path, lockFactory); } else { return new NIOFSDirectory(path, lockFactory); } }
覆盖方法1:sync()
在父类abstract Directory声明如下:
/** Ensure that any writes to this file are moved to * stable storage. Lucene uses this to properly commit * changes to the index, to prevent a machine/OS crash * from corrupting the index. */ public void sync(String name) throws IOException {}
子类abstract FSDirectory进行了override
@Override
public void sync(String name) throws IOException {
ensureOpen();
File fullFile = new File(directory, name);
boolean success = false;
int retryCount = 0;
IOException exc = null;
while(!success && retryCount < 5) {
retryCount++;
RandomAccessFile file = null;
try {
try {
file = new RandomAccessFile(fullFile, "rw");
file.getFD().sync();
success = true;
} finally {
if (file != null)
file.close();
}
} catch (IOException ioe) {
if (exc == null)
exc = ioe;
try {
// Pause 5 msec
Thread.sleep(5);
} catch (InterruptedException ie) {
throw new ThreadInterruptedException(ie);
}
}
}
if (!success)
// Throw original exception
throw exc;
}
覆盖方法2:getLockID()
在父类abstract Directory声明如下:
/** * Return a string identifier that uniquely differentiates * this Directory instance from other Directory instances. * This ID should be the same if two Directory instances * (even in different JVMs and/or on different machines) * are considered "the same index". This is how locking * "scopes" to the right index. */ public String getLockID() { return this.toString(); } @Override public String toString() { return super.toString() + " lockFactory=" + getLockFactory(); }
子类abstract FSDirectory进行了override
@Override public String getLockID() { ensureOpen(); String dirName; // name to be hashed try { dirName = directory.getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e.toString(), e); } byte digest[]; synchronized (DIGESTER) { digest = DIGESTER.digest(dirName.getBytes()); } StringBuilder buf = new StringBuilder(); buf.append("lucene-"); for (int i = 0; i < digest.length; i++) { int b = digest[i]; buf.append(HEX_DIGITS[(b >> 4) & 0xf]); buf.append(HEX_DIGITS[b & 0xf]); } return buf.toString(); }