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的锁: 关键的实现难点是 ...
随机推荐
- Manthan, Codefest 16
暴力 A - Ebony and Ivory import java.util.*; import java.io.*; public class Main { public static void ...
- PHP、Java对称加密中的AES加密方法
PHP AES加密 <?php ini_set('default_charset','utf-8'); class AES{ public $iv = null; public $key = n ...
- POJ3368 Frequent values(RMQ线段树)
题目大概说给一个递增序列,询问区间出现最多的数. 用莫队算法比较直观,虽然应该会T..好像也可以主席树..不过题目给的序列是有序的,因而相同的数会聚在一起. 考虑把序列分成一段一段,使每段都包含极大的 ...
- 由case 和 break 引发的思考
我在使用case 语句的时候,发现结果不对劲,原来我是忽略了break这个语句的添加 然后,我要反思的是,这样基本的语句,我这样的错误也能犯,证明我自己之前还没有真正掌握这个语句的使用. 所以,真正地 ...
- HTML与HTML5笔记
doctype作用 1.告诉浏览器使用什么样的html或者xhtml规范来解析html文档 2.影响浏览器的渲染模式. 浏览器解析css的两种渲染模式:标准模式strict mode和怪异模式quir ...
- word多级编号,如何让第一级为大写“一”,其他级别均为小写1.
自定义里面设置了第一级为大写,2级.3级首字跟着变为大写,是因为2.3级没有勾选"正规形式编号",如图:
- Leetcode Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- ACM: HDU 2544 最短路-Dijkstra算法
HDU 2544最短路 Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Descrip ...
- 转:Web页面通过URL地址传递参数常见问题及检测方法
Web页面即我们在浏览器中所看到的网页,在Web应用程序中,其页面往往需要进行动态切换和数据交互,页面间的数据常规传递方法有多种,本文主要介绍Web页面处理程序中常见的URL地址参数传递方法,包括概述 ...
- [深入浅出Windows 10]QuickCharts图表控件库解析
13.4 QuickCharts图表控件库解析 QuickCharts图表控件是Amcharts公司提供的一个开源的图表控件库,这个控件库支持WPF.Silverlight.和Windows等 ...