Chinaunix首页 | 论坛 | 博客
  • 博客访问: 137759
  • 博文数量: 37
  • 博客积分: 277
  • 博客等级: 二等列兵
  • 技术积分: 326
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-17 21:06
文章分类
文章存档

2016年(2)

2015年(11)

2014年(5)

2013年(7)

2012年(4)

2011年(8)

分类: Java

2014-02-07 16:26:52

由于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);
}
}
}


阅读(6859) | 评论(0) | 转发(1) |
0

上一篇:网站 developerWorks

下一篇:URL编码与解码

给主人留下些什么吧!~~