Browse Source

Pipe & FileLock

master
louzin 6 months ago
parent
commit
a0750526cc
  1. 47
      src/doc/FileLock.md
  2. 28
      src/doc/pipe.md
  3. 5
      src/main/java/com/louzin/niodemo/filelock/fileLockCRUD.java
  4. 32
      src/main/java/com/louzin/niodemo/pipe/pipecrud.java

47
src/doc/FileLock.md

@ -0,0 +1,47 @@
# FileLock
在OS中很常见,用来避免多个程序同时修改同一个文件造成的不同步问题
给一个文件加锁,同一时间只有一个程序能修改此文件
**文件锁是进程级别的,不是线程级别的**
文件锁可以解决多个进程之间的不同步,但不能解决多线程的问题
文件锁是JVM持有的,一但获取到文件锁,要调用
- release()
- 关闭FileChannel对象
- JVM退出
才会释放这个锁
## 分类
### 排他锁
独占锁,仅该进程可操作,其他进程不能操作,直至释放锁
### 共享锁
其他进程仅可读,直到释放锁,是线程安全的
```java
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
FileChannel fileChannel = new FileOutputStream("./1.txt").getChannel;
File lock = fileChannel.lock();
lock.release();
```
## 获取文件锁的方法
- lock():排他锁
- lock(long position,long size,boolean shared):第一、二个参数表示加锁位置,第三个参数表示是否为共享锁
- tryLock():排他锁
- tryLock(long position,long size,boolean shared):自定义锁,若指定共享锁,则其他进程只读,若尝试写入会抛出异常
### lock & trylock
- lock:阻塞
- trylock:非阻塞,获取成功返回当前对象,否则为null
## 其他方法
### boolean isShared()
### boolean isValid()
此文件锁是否还有效
在某些os上对某个文件枷锁后,不能对该文件使用通道映射

28
src/doc/pipe.md

@ -0,0 +1,28 @@
# Pipe
Java NIO管道是线程之间的单向数据连接
Pipe有一个source和一个sink通道,数据会写到sink,从source读取
## Pipe CRUD
```java
public void createPipe() throws IOException {
//Get Pipe
Pipe open = Pipe.open();
//Get sink Pipe
Pipe.SinkChannel sink = open.sink();
//Get Buffer
ByteBuffer allocate = ByteBuffer.allocate(1024);
//write into sink Pipe
allocate.put("louzin".getBytes(StandardCharsets.UTF_8));
allocate.flip();
sink.write(allocate);
//Get source Pipe
Pipe.SourceChannel source = open.source();
//create Buffer and read source Pipe
ByteBuffer allocate1 = ByteBuffer.allocate(1024);
int length = source.read(allocate1);
allocate1.flip();
System.out.println(new String(allocate1.array(),0,length));
//close Pipe
}
```

5
src/main/java/com/louzin/niodemo/filelock/fileLockCRUD.java

@ -0,0 +1,5 @@
package com.louzin.niodemo.filelock;
public class fileLockCRUD {
}

32
src/main/java/com/louzin/niodemo/pipe/pipecrud.java

@ -0,0 +1,32 @@
package com.louzin.niodemo.pipe;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.StandardCharsets;
public class pipecrud {
@Test
public void createPipe() throws IOException {
//Get Pipe
Pipe open = Pipe.open();
//Get sink Pipe
Pipe.SinkChannel sink = open.sink();
//Get Buffer
ByteBuffer allocate = ByteBuffer.allocate(1024);
//write into sink Pipe
allocate.put("louzin".getBytes(StandardCharsets.UTF_8));
allocate.flip();
sink.write(allocate);
//Get source Pipe
Pipe.SourceChannel source = open.source();
//create Buffer and read source Pipe
ByteBuffer allocate1 = ByteBuffer.allocate(1024);
int length = source.read(allocate1);
allocate1.flip();
System.out.println(new String(allocate1.array(),0,length));
//close Pipe
}
}
Loading…
Cancel
Save