操作系统概念 10.1.2 文件锁定的JAVA示例

本文介绍了一个简单的Java程序,演示如何对文件的前半部分获取独占锁,对后半部分获取共享锁。程序首先尝试获取独占锁并修改数据,然后释放锁,再获取共享锁读取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * A simple program demonstrating file locking.
 * This program acquires an exclusive lock on the
 * first half of the file and a shared lock on the second half.
 *
 * Usage
 *	java LockingExample <input file>
 *
 * Figure 11.2
 *
 * @author Gagne, Galvin, Silberschatz
 * Operating System Concepts - Ninth Edition
 * Copyright John Wiley & Sons - 2013.
 */

import java.io.*;
import java.nio.channels.*;

public class LockingExample {
	public static final boolean EXCLUSIVE = false;
	public static final boolean SHARED = true;

   public static void main(String args[]) throws IOException {
	if (args.length != 1) {
		System.err.println("Usage: java LockingExample <input file>");
		System.exit(0);
	}

	FileLock sharedLock = null;
	FileLock exclusiveLock = null;

	try {
     		RandomAccessFile raf = new RandomAccessFile(args[0], "rw"); 

		// get the channel for the file
     		FileChannel channel = raf.getChannel();

		System.out.println("trying to acquire lock ...");
		// this locks the first half of the file - exclusive
		exclusiveLock = channel.lock(0, raf.length()/2, EXCLUSIVE);
		System.out.println("lock acquired ...");

		/**
		 * Now modify the data  . . .
		 */

		try {
			// sleep for 10 seconds
			Thread.sleep(10000);
		}
		catch (InterruptedException ie) { }

		// release the lock
		exclusiveLock.release();
		System.out.println("lock released ...");

		// this locks the second half of the file - shared 
		sharedLock = channel.lock(raf.length()/2 + 1, raf.length(), SHARED);
		
		/**
		 * Now read the data  . . .
		 */

		// release the lock
		exclusiveLock.release();
	} catch (java.io.IOException ioe) {
		System.err.println(ioe);
	}
      	finally {
		if (exclusiveLock != null)
       			exclusiveLock.release();
		if (sharedLock != null)
       			sharedLock.release();
     	}
   }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值