java FileLock
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.io.RandomAccessFile;
import java.util.Random; /**
* Test locking with FileChannel. Run one copy of this code with arguments
* "-w /tmp/locktest.dat" and one or more copies with "-r /tmp/locktest.dat" to
* see the interactions of exclusive and shared locks. Note how too many readers
* can starve out the writer. Note: The filename you provide will be
* overwritten. Substitute an appropriate temp filename for your favorite OS.
*
* Created April, 2002
*
* @author Ron Hitchens (ron@ronsoft.com)
*/
public class LockTest {
private static final int SIZEOF_INT = ;
private static final int INDEX_START = ;
private static final int INDEX_COUNT = ;
private static final int INDEX_SIZE = INDEX_COUNT * SIZEOF_INT;
private ByteBuffer buffer = ByteBuffer.allocate(INDEX_SIZE);
private IntBuffer indexBuffer = buffer.asIntBuffer();
private Random rand = new Random(); public static void main(String[] argv) throws Exception {
boolean writer = false;
String filename;
// if (argv.length != 2) {
// System.out.println("Usage: [ -r | -w ] filename");
// return;
// } String temp[]={"-w","xxx.txt"};
argv=temp;
writer = argv[].equals("-w");
filename = argv[];
RandomAccessFile raf = new RandomAccessFile(filename, (writer) ? "rw"
: "r");
FileChannel fc = raf.getChannel();
LockTest lockTest = new LockTest();
if (writer) {
lockTest.doUpdates(fc);
} else {
lockTest.doQueries(fc);
}
} // ----------------------------------------------------------------
// Simulate a series of read-only queries while
// holding a shared lock on the index area
void doQueries(FileChannel fc) throws Exception {
while (true) {
println("trying for shared lock...");
FileLock lock = fc.lock(INDEX_START, INDEX_SIZE, true);
int reps = rand.nextInt() + ;
for (int i = ; i < reps; i++) {
int n = rand.nextInt(INDEX_COUNT);
int position = INDEX_START + (n * SIZEOF_INT);
buffer.clear();
fc.read(buffer, position);
int value = indexBuffer.get(n);
println("Index entry " + n + "=" + value);
// Pretend to be doing some work
Thread.sleep();
}
lock.release();
println("<sleeping>");
Thread.sleep(rand.nextInt() + );
}
} // Simulate a series of updates to the index area
// while holding an exclusive lock
void doUpdates(FileChannel fc) throws Exception {
while (true) {
println("trying for exclusive lock...");
FileLock lock = fc.lock(INDEX_START, INDEX_SIZE, false);
updateIndex(fc);
lock.release();
println("<sleeping>");
Thread.sleep(rand.nextInt() + );
}
} // Write new values to the index slots
private int idxval = ; private void updateIndex(FileChannel fc) throws Exception {
// "indexBuffer" is an int view of "buffer"
indexBuffer.clear();
for (int i = ; i < INDEX_COUNT; i++) {
idxval++;
println("Updating index " + i + "=" + idxval);
indexBuffer.put(idxval);
// Pretend that this is really hard work
Thread.sleep();
}
// leaves position and limit correct for whole buffer
buffer.clear();
fc.write(buffer, INDEX_START);
} // ----------------------------------------------------------------
private int lastLineLen = ; // Specialized println that repaints the current line
private void println(String msg) {
System.out.print("\r ");
System.out.print(msg);
for (int i = msg.length(); i < lastLineLen; i++) {
System.out.print(" ");
}
System.out.print("\r");
System.out.flush();
lastLineLen = msg.length();
}
}
java FileLock的更多相关文章
- Spark案例分析
一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...
- Java使用FileLock实现Java进程互斥锁
原理:JDK的nio包中FileLock实现类似Linux fcntl的文件锁, 可使文件被进程互斥访问. 借助此功能, 可以实现强大的Java进程互斥锁, 从而在应用层面保证同一时间只有惟一的Ja ...
- Java NIO中的FileLock(文件锁)
FileLock,文件锁. 文件锁在OS中很常见,如果多个程序同时访问.修改同一个文件,很容易因为文件数据不同步而出现问题.给文件加一个锁,同一时间,只能有一个程序修改此文件,或者程序都只能读此文件, ...
- Java NIO概述
Java NIO 由以下几个核心部分组成: Channels Buffers Selectors 虽然 Java NIO 中除此之外还有很多类和组件,但在我看来,Channel,Buffer 和 Se ...
- JAVA NIO FileChannel 内存映射文件
文件通道总是阻塞式的. 文件通道不能创建,只能通过(RandomAccessFile.FileInputStream.FileOutputStream)getChannel()获得,具有与File ...
- Java NIO (转)
Java NIO提供了与标准IO不同的IO工作方式: Channels and Buffers(通道和缓冲区):标准的IO基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(B ...
- Java - NIO
java.nio:NIO-2: NIO 面向流的IO体系一次只能处理一个或多个字节/字符,直至读取所有字节/符,且流中的数据不能前后移动.效率低,当数据源中没有数据时会阻塞线程.Java-4提供的新A ...
- 【转】java NIO 相关知识
原文地址:http://www.iteye.com/magazines/132-Java-NIO Java NIO(New IO)是从Java 1.4版本开始引入的一个新的IO API,可以替代标准的 ...
- java 锁!
问题:如何实现死锁. 关键: 1 两个线程ta.tb 2 两个对象a.b 3 ta拥有a的锁,同时在这个锁定的过程中,需要b的锁:tb拥有b的锁,同时在这个锁定的过程中,需要a的锁: 关键的实现难点是 ...
随机推荐
- BZOJ1001 [BeiJing2006]狼抓兔子(平面图最小割转最短路)
..和HDU3870类似..注意n=1和m=1的情况. #include<cstdio> #include<cstring> #include<queue> #in ...
- Silverlight
http://kb.cnblogs.com/zt/silverlight/ http://www.cnblogs.com/gnielee/archive/2010/01/15/silverlight- ...
- The 2015 China Collegiate Programming Contest G. Ancient Go hdu 5546
Ancient Go Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total ...
- 洛谷 P1803 凌乱的yyy Label:Water 贪心
题目背景 快noip了,yyy很紧张! 题目描述 现在各大oj上有n个比赛,每个比赛的开始.结束的时间点是知道的. yyy认为,参加越多的比赛,noip就能考的越好(假的) 所以,他想知道他最多能参加 ...
- NOIp 2013 #1 积木大赛 Label:有趣的模拟
题目描述 春春幼儿园举办了一年一度的“积木大赛”.今年比赛的内容是搭建一座宽度为n的大厦,大厦可以看成由n块宽度为1的积木组成,第i块积木的最终高度需要是hi. 在搭建开始之前,没有任何积木(可以看成 ...
- [Cocos2d-x For WP8]DrawPrimitives画图
在Silverlight框架的WP8应用程序里面,我们画几何图形的时候会通过Line等等的类在用C#代码或者在XAML上画图,那么在Cocos2d-x For WP8里面我们一样也可以实现这样的功能. ...
- Linux下memcached安装和启动方法
Linux下memcached安装和启动方法 1. 首先下载memcached 和 libevent 包. Memcached用到了libevent这个库用于Socket的处理.下面是下载的两个包文件 ...
- MongoDB数据库的简介及安装
一.MongoDB数据库简介 简介 MongoDB是一个高性能,开源,无模式的,基于分布式文件存储的文档型数据库,由C++语言编写,其名称来源取自“humongous”,是一种开源的文档数据库──No ...
- MongoDB设置访问权限、设置用户
MongoDB已经使用很长一段时间了,基于MongoDB的数据存储也一直没有使用到权限访问(MongoDB默认设置为无权限访问限制),今天特地花了一点时间研究了一下,研究成果如下: 注:研究成果基于W ...
- [LintCode] Length of Last Word 求末尾单词的长度
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the l ...