Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6211758
  • 博文数量: 2759
  • 博客积分: 1021
  • 博客等级: 中士
  • 技术积分: 4091
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-11 14:14
文章分类

全部博文(2759)

文章存档

2019年(1)

2017年(84)

2016年(196)

2015年(204)

2014年(636)

2013年(1176)

2012年(463)

分类: Java

2014-02-09 10:18:42

原文地址:Java 进程同步实现 作者:oneNotEqualsTow

由于jdk自身没有提供进程同步到工具类,但是项目又有一个这样的需求,就想着自己试着实现一个,基本想法是通过nio提供的FileChannel + FileLock 实现,完成了一部分,不知道思路是不是正确的,欢迎拍砖!!!

public class ProcessSynchron {


private static ExecutorService waiting = Executors.newCachedThreadPool();


private static Map sameProcessOpenStreams = new HashMap();

private static Map fileOpenCounter = new HashMap();


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 result = waiting.submit(new Callable() {
@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);
}
}
}


阅读(589) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~