java中的FileLok与ReentrantReadWriteLock选择哪个实现文件的读写?

由于现在数据都是存储在数据库上的,而存储在文件上的相对来说很少,但有时还是需要多个线程来进行文件的读与写。选择FileLock还是选择ReetrantReadWriteLock?
经过自己的测试发现FileLock是多个进程之间对文件的访问,或者不同的JVM实例之间的操作访问。一个JVM只能拥有一个FileLock。所以在一个程序之间要实现线程之间的文件访问就不应该使用FileLock。而应该使用ReetrantReadWriteLock。下面是我实现的对于文件的访问,跟FileLock的共享锁差不多。就是读可以多个线程同时访问文件,写只能由一个线程独占文件,写锁阻塞直到获得锁。当一个线程占用读锁时,写锁阻塞,读锁不阻塞。 当一个线程占用写锁时,其他线程的读锁和写锁都阻塞,如下:

public class FileLockUtils {
    private final static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public static void writeStringToFile(final File file, final String data,final String encoding) {
        lock.writeLock().lock();
        try{
            OutputStreamWriter writer=new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)),Charset.forName(encoding));
             writer.write(data);
             writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
             lock.writeLock().unlock();
        }
    }

    public static String readFileToString(final File file, final String encoding) {
          lock.readLock().lock();
          try {
              InputStreamReader reader = new InputStreamReader(new BufferedInputStream(new FileInputStream(file)),Charset.forName(encoding));
              char[] buffer = new char[1024];
              StringBuilder builder = new StringBuilder();
              int len=-1;
              while ((len=reader.read(buffer))!=-1){
                  builder.append(buffer,0,len);
              }
              reader.close();
             return builder.toString();
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              lock.readLock().unlock();
          }
        return null;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值