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的更多相关文章

  1. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  2. Java使用FileLock实现Java进程互斥锁

    原理:JDK的nio包中FileLock实现类似Linux fcntl的文件锁, 可使文件被进程互斥访问.  借助此功能, 可以实现强大的Java进程互斥锁, 从而在应用层面保证同一时间只有惟一的Ja ...

  3. Java NIO中的FileLock(文件锁)

    FileLock,文件锁. 文件锁在OS中很常见,如果多个程序同时访问.修改同一个文件,很容易因为文件数据不同步而出现问题.给文件加一个锁,同一时间,只能有一个程序修改此文件,或者程序都只能读此文件, ...

  4. Java NIO概述

    Java NIO 由以下几个核心部分组成: Channels Buffers Selectors 虽然 Java NIO 中除此之外还有很多类和组件,但在我看来,Channel,Buffer 和 Se ...

  5. JAVA NIO FileChannel 内存映射文件

      文件通道总是阻塞式的. 文件通道不能创建,只能通过(RandomAccessFile.FileInputStream.FileOutputStream)getChannel()获得,具有与File ...

  6. Java NIO (转)

    Java NIO提供了与标准IO不同的IO工作方式: Channels and Buffers(通道和缓冲区):标准的IO基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(B ...

  7. Java - NIO

    java.nio:NIO-2: NIO 面向流的IO体系一次只能处理一个或多个字节/字符,直至读取所有字节/符,且流中的数据不能前后移动.效率低,当数据源中没有数据时会阻塞线程.Java-4提供的新A ...

  8. 【转】java NIO 相关知识

    原文地址:http://www.iteye.com/magazines/132-Java-NIO Java NIO(New IO)是从Java 1.4版本开始引入的一个新的IO API,可以替代标准的 ...

  9. java 锁!

    问题:如何实现死锁. 关键: 1 两个线程ta.tb 2 两个对象a.b 3 ta拥有a的锁,同时在这个锁定的过程中,需要b的锁:tb拥有b的锁,同时在这个锁定的过程中,需要a的锁: 关键的实现难点是 ...

随机推荐

  1. 使用Soapui测试webservice接口

    本来想自己写一个的,但下面这个资料比较详细(截图和步骤细节),就省事了,具体内容见: http://blog.csdn.net/oracle_microsoft/article/details/568 ...

  2. ZOJ3201 Tree of Tree(树形DP)

    题目大概求一棵树中大小为k的子树的最大权和. dp[u][k]表示以u为根的子树中包含u结点的大小为k的子树的最大权和,然后树上背包转移转移很容易.. #include<cstdio> # ...

  3. HDU3157 Crazy Circuits(有源汇流量有上下界网络的最小流)

    题目大概给一个电路,电路上有n+2个结点,其中有两个分别是电源和负载,结点们由m个单向的部件相连,每个部件都有最少需要的电流,求使整个电路运转需要的最少电流. 容量网络的构建很容易,建好后就是一个有源 ...

  4. 将DLL中资源导出到指定文件夹

    File.WriteAllBytes( @"C:\Windows\System32\MyDll.dll", Resources.MyDll );

  5. hihoCoder#1384 : Genius ACM

    对于一个固定的区间$[l,r]$,显然只要将里面的数字从小到大排序后将最小的$m$个和最大的$m$个配对即可. 如果固定左端点,那么随着右端点的右移,$SPD$值单调不降,所以尽量把右端点往右移,贪心 ...

  6. 【BZOJ1036】[ZJOI2008]树的统计Count 树链剖分

    [BZOJ1036][ZJOI2008]树的统计Count Description 一棵树上有n个节点,编号分别为1到n,每个节点都有一个权值w.我们将以下面的形式来要求你对这棵树完成一些操作: I. ...

  7. 图解Storm

    问题导读:1.你认为什么图形可以显示hadoop与storm的区别?(电梯)2.本文是如何形象讲解hadoop与storm的?(离线批量处理.实时流式处理)3.hadoop map/reduce对应s ...

  8. div+css定位position详解

    div+css定位position详解 1.div+css中的定位position 最主要的两个属性:属性 absolute(绝对定位) relative(相对定位),有他们才造就了div+css布局 ...

  9. 【BZOJ】2879: [Noi2012]美食节

    题意 \(m\)个厨师,\(n\)种菜,每种菜需要做\(p_i\)份,每个厨师做第\(i\)种菜用时\(t_{i, j}\).一个厨师做完一道菜才能做下一道.每份菜的时间是这个厨师做完这道菜的用时加上 ...

  10. 两种不同png图片的在项目中的运用

    png图片主要分为两种 png-8和png-24. PNG8和PNG24后面的数字则是代表这种PNG格式最多可以索引和存储的颜色值.”8″代表2的8次方也就是256色,而24则代表2的24次方大概有1 ...