分类: Java
2014-02-07 16:26:52
由于jdk自身没有提供进程同步到工具类,但是项目又有一个这样的需求,就想着自己试着实现一个,基本想法是通过nio提供的FileChannel + FileLock 实现,完成了一部分,不知道思路是不是正确的,欢迎拍砖!!!
public class ProcessSynchron {
private static ExecutorService waiting = Executors.newCachedThreadPool();
private static Map
private static Map
public static synchronized ProcessSynchron getSynchron(String synchronName) throws IOException{
FileOutputStream fileStream;
if (sameProcessOpenStreams.containsKey(synchronName)) {
fileOpenCounter.put(synchronName, fileOpenCounter.get(synchronName) + 1);
fileStream = sameProcessOpenStreams.get(synchronName);
} else {
fileStream = new FileOutputStream(System.getProperty("java.io.tmpdir") + File.separator + synchronName);
sameProcessOpenStreams.put(synchronName, fileStream);
fileOpenCounter.put(synchronName, 1);
}
return new ProcessSynchron(synchronName, fileStream);
}
private static synchronized void realseGlobal(String lockName2) {
Integer counter = fileOpenCounter.get(lockName2);
if(-- counter == 0){
// sameProcessOpenStreams.get(lockName2).close();
}
}
private String lockName;
private FileChannel fileLock;
private ProcessSynchron(String lockName,FileOutputStream fileOutputStream) {
fileLock = fileOutputStream.getChannel();
this.lockName = lockName;
}
public void lock() {
try {
fileLock.lock();
} catch (IOException e) {
throw new AccquireLockInternalException(e);
}
}
public boolean tryLock(long waitTimes, TimeUnit timeUnit)
throws TimeoutException {
Future
@Override
public Boolean call() throws Exception {
return fileLock.lock() != null;
}
});
try {
return result.get(waitTimes, timeUnit);
} catch (InterruptedException e) {
return false;
} catch (ExecutionException e) {
throw new AccquireLockInternalException(e);
}
}
public void release() {
try {
if (fileLock.isOpen()) {
realseGlobal(lockName);
fileLock.close();
}
} catch (IOException e) {
throw new AccquireLockInternalException(e);
}
}
}