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. iOS instancetype or id ?

    The id type simply says a method will return a reference to an object. It could be any object of any ...

  2. storm安装笔记以及提交拓扑任务

    Storm -- Distributed and fault-tolerant realtime computation 这是一个分布式的.容错的实时计算系统 把Storm依赖组件的版本贴出来供各位参 ...

  3. POJ 2480 (约数+欧拉函数)

    题目链接: http://poj.org/problem?id=2480 题目大意:求Σgcd(i,n). 解题思路: 如果i与n互质,gcd(i,n)=1,且总和=欧拉函数phi(n). 如果i与n ...

  4. CSS抗锯齿 font-smoothing 属性介绍

    CSS3里面加入了一个“-webkit-font-smoothing”属性. 这个属性可以使页面上的字体抗锯齿,使用后字体看起来会更清晰舒服. 加上之后就顿时感觉页面小清晰了. 淘宝也在用哦! 它有三 ...

  5. a little about hashtable vs dictionary

    使用Hashtable没有任何优点,因为在.net2.0以后已经被Dictionary<Tkey,TValue>所代替. 他们两者的区别是,根据stackoverflow Dictiona ...

  6. BZOJ4513: [Sdoi2016]储能表

    Description 有一个 n 行 m 列的表格,行从 0 到 n−1 编号,列从 0 到 m−1 编号.每个格子都储存着能量.最初,第 i 行第 j 列的格子储存着 (i xor j) 点能量. ...

  7. 深入浅出 - Android系统移植与平台开发(三)- 编译并运行Android4.0模拟器

    作者:唐老师,华清远见嵌入式学院讲师. 1.   编译Android模拟器 在Ubuntu下,我们可以在源码里编译出自己的模拟器及SDK等编译工具,当然这个和在windows里下载的看起来没有什么区别 ...

  8. GO语言练习:多返回值函数

    1.代码 2.运行 1.代码 package main import ( "fmt" "strconv" ) func getValue(n int) (flo ...

  9. Search Ads 已经在美国区上线 - iOS 移动开发周报(46)

    Search Ads 已经在美国区上线 - iOS 移动开发周报(46) 新闻 Search Ads 上线 苹果的 AppStore 搜索广告终于 正式上线了 https://developer.ap ...

  10. odoo XMLRPC 新库 OdooRPC 尝鲜

    无意中发现了python居然有了OdoRPC的库,惊喜之下赶紧尝试一番,比XMLRPC简洁了不少,机制看样子是利用的JsonRPC. #原文出自KevinKong的博客http://www.cnblo ...