|
| 1 | +package org.javacore.nio; |
| 2 | + |
| 3 | +import java.io.FileNotFoundException; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.RandomAccessFile; |
| 6 | +import java.nio.ByteBuffer; |
| 7 | +import java.nio.MappedByteBuffer; |
| 8 | +import java.nio.channels.FileChannel; |
| 9 | +import java.nio.channels.FileLock; |
| 10 | + |
| 11 | +/* |
| 12 | + * Copyright [2015] [Jeff Lee] |
| 13 | + * |
| 14 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 15 | + * you may not use this file except in compliance with the License. |
| 16 | + * You may obtain a copy of the License at |
| 17 | + * |
| 18 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 19 | + * |
| 20 | + * Unless required by applicable law or agreed to in writing, software |
| 21 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 22 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 23 | + * See the License for the specific language governing permissions and |
| 24 | + * limitations under the License. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @author Jeff Lee |
| 29 | + * @since 2015-10-17 15:17:04 |
| 30 | + * 映射文件的使用 |
| 31 | + */ |
| 32 | +public class LockingMappedFiles { |
| 33 | + static final int LENGTH = 0x8FFFFFF; // 128 MB |
| 34 | + static FileChannel fc; |
| 35 | + |
| 36 | + public static void main(String[] args) throws IOException { |
| 37 | + fc = new RandomAccessFile("data.txt" , "rw").getChannel(); |
| 38 | + MappedByteBuffer out = fc.map(FileChannel.MapMode.READ_WRITE, |
| 39 | + 0 , LENGTH); |
| 40 | + for (int i = 0;i < LENGTH; i++) |
| 41 | + out.put((byte)'x'); |
| 42 | + new LockAndModify(out,0,0 + LENGTH/3); |
| 43 | + new LockAndModify(out,LENGTH/2,LENGTH/2 + LENGTH/4); |
| 44 | + } |
| 45 | + |
| 46 | + // 线程 |
| 47 | + private static class LockAndModify extends Thread { |
| 48 | + private ByteBuffer buffer; |
| 49 | + private int start,end; |
| 50 | + |
| 51 | + LockAndModify(ByteBuffer mbb, int start, int end) { |
| 52 | + this.start = start; |
| 53 | + this.end = end; |
| 54 | + mbb.limit(end); |
| 55 | + mbb.position(start); |
| 56 | + buffer = mbb.slice(); |
| 57 | + start(); |
| 58 | + } |
| 59 | + |
| 60 | + public void run() { |
| 61 | + try { |
| 62 | + // 从FileChannel获取文件加锁对象,并加锁 |
| 63 | + FileLock fl = fc.lock(start,end,false); |
| 64 | + System.out.println("Locked: " + start + " to " + end); |
| 65 | + // 写入数据 |
| 66 | + while (buffer.position() < buffer.limit() - 1) |
| 67 | + buffer.put((byte)(buffer.get() + 1)); |
| 68 | + fl.release(); |
| 69 | + System.out.println("Released: " + start + " to " + end); |
| 70 | + } catch (IOException e) { |
| 71 | + throw new RuntimeException(e); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments