JAVA多线程读写文件如何做到线程安全?(文件锁,FileChannel)

使用FileChannel读取下载文件 使用FileChannel读取下载文件前言一、FileChannel是什么?二、FileChannal的方法介绍1.open2.read3.write4.lock总结 前言 FileChannal的理解和使用场景 对于文件的复制,平时我们都是使用输入输出流进行操作,利用源文件创建出一个输入流,然后利用目标文件创建出一个输出流,最后将输入流的数据读取写入到输出流中。这样也是可以进行操作的。但是利用fileChannel是很有用的一个方式。它能直接连接输入输出流的文件通道,将数据直接写入到目标文件中去。而且效 阅读详情

 

 

NIO提升性能

在JAVA的标准I/O中,提供了基于流的I/O实现,即InputStream和OutputStream。这种基于流的实现以字节为单位处理数据。NIO是New I/O的简称,表示一套新的JAVA I/O标准。在Jdk 1.4中开始引入,它具有以下特性:

  • 为所有的原始类型提供(Buffer)缓存支持;
  • 使用Java.nio.charset.Charset作为字符集编码解码解决方案;
  • 增加通道(Cahnnel)对象,作为新的原始I/O抽象;
  • 支持锁和内存映射文件的文件访问接口;
  • 提供了基于Selector的异步网络I/O。

与流式的I/O不容,NIO是基于块(Block)的,它以块为基本单位处理数据。在NIO中,最为重要的2个组件是缓冲Buffer和通道Channel。缓冲是一块连续的内存块,是NIO读写数据的中转地。通道表示缓冲数据的源头或者目的地,它用于向缓冲读取或者写入数据,是访问缓冲的接口。

在这里插入图片描述

多线程读写同一个文件有哪些场景需要同步处理?

  • 有线程正在读文件,另开辟线程写文件;
  • 有线程正在写文件,另开辟线程读文件;
  • 有线程正在写文件,另开辟线程写文件

总之,读写互斥,写读互斥,写写互斥,只有读读相容(可以异步)。

使用对文件加锁的方式做到线程安全

FileInputStream、FileOutputStream、RandomAccessFile均可得到FileChannel对象,对文件锁进行操作。
独占锁tryLock()

FileChannel的tryLock()是非阻塞的,也就是说,在发现文件被锁住的时候,直接返回null,并且抛出异常,如果没有锁住,直接返回该文件的文件锁。
它是独占锁,就是只能被一个线程持有,它能禁止其他线程获取共享锁,可用于写文件。

  while (true) {
                try {
                    fileLock = fileChannel.tryLock();//独占锁
                    break;
                } catch (Exception e) {
                    System.out.println("有其他线程正在操作该文件,当前线程" + Thread.currentThread().getName());
                }
            }

共享锁tryLock(0, Long.MAX_VALUE, true)

FileChannel的tryLock(0, Long.MAX_VALUE, true)是非阻塞的,在发现文件被锁住的时候,直接返回null,并且抛出异常,如果没有锁住,直接返回该文件的文件锁。
它是共享锁,能被多个线程同时持有,它能禁止其他线程获取独占锁,可用于读文件。

while (true) {
                try {
                    fileLock = fileChannel.tryLock(0, Long.MAX_VALUE, true);//共享锁
                    break;
                } catch (Exception e) {
                    System.out.println("有其他线程正在操作该文件,当前线程" + Thread.currentThread().getName());
                }
            }

独占锁lock()

而FileChannel的lock()是阻塞的,在文件被锁定的情况下,会保持阻塞,直到获得该锁为止。

fileLock = fileChannel.lock();
......

写文件线程安全

 /**
     * 将str写入文件,同步操作,独占锁
     */
    public void writeStr2ReplaceFileSync(String str, String pathFile, IOListener ioListener) {
        File file;
        try {
            file = FileUtils.createFile(pathFile);
        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail("文件创建失败,请检查路径是否合法以及读写权限");
            return;
        }
        FileOutputStream fileOutputStream = null;
        FileChannel fileChannel = null;
        FileLock fileLock = null;//文件锁
        try {

            /**
             * 写文件
             */
            fileOutputStream = new FileOutputStream(file);
            fileChannel = fileOutputStream.getChannel();
            while (true) {
                try {
                    fileLock = fileChannel.tryLock();//独占锁
                    break;
                } catch (Exception e) {
                    System.out.println("有其他线程正在操作该文件,当前线程" + Thread.currentThread().getName());
                }
            }
            if (fileLock != null) {
                int len = 0;
                long current = file.length();
                if (isRunning ) {
                    fileChannel.write(ByteBuffer.wrap(str.getBytes()));
                    current += len;
                    LogUtils.log("当前线程" + Thread.currentThread().getName());
                    ioListener.onLoading(str.getBytes(), current, str.length());
                }else {
                    //中断
                    ioListener.onInterrupted();
                }
                if (fileLock != null && fileLock.isValid()) {
                    LogUtils.log("release-write-lock");
                    fileLock.release();
                }
                close(fileChannel);
                close(fileOutputStream);
                if (file.length() == str.getBytes().length) {
                    ioListener.onCompleted(file);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
        } finally {
        }
    }

读文件线程安全

  /**
     * 同步读取,共享锁,但无法同时进行写操作
     *
     * @param ioListener
     */
    public void read2StrSync(String pathFile, IOListener ioListener) {
        FileInputStream fileInputStream = null;
        FileChannel fileChannel = null;
        FileLock fileLock = null;//文件锁

        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        try {

            /**
             * 读文件
             */

            fileInputStream = new FileInputStream(pathFile);
            fileChannel = fileInputStream.getChannel();
            while (true) {
                try {
                    fileLock = fileChannel.tryLock(0, Long.MAX_VALUE, true);//共享锁
                    break;
                } catch (Exception e) {
                    System.out.println("有其他线程正在操作该文件,当前线程" + Thread.currentThread().getName());
                }
            }
            if (fileLock != null) {

                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int len = 0;
                long current = 0;
                while (isRunning && (len = fileChannel.read(byteBuffer)) != -1) {
                    //0,byteBuffer.position(),必须写这个,否则GG,读取文件错乱
                    byteArrayOutputStream.write(byteBuffer.array(),0,byteBuffer.position());
                    current += len;
                    ioListener.onLoading("", current, fileChannel.size());
                    byteBuffer.clear();
                }
                if (fileLock != null && fileLock.isValid()) {
                LogUtils.log("release-read-lock");
                    fileLock.release();
                }
                close(fileChannel);
                close(fileInputStream);
                //中断
                if (len != -1) {
                    ioListener.onInterrupted();
                } else {
                    ioListener.onCompleted(byteArrayOutputStream.toString("utf-8"));

                }
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());

        } finally {


        }
    }

小编写的IOListener接口,用于回调

public interface IOListener<T> {
    public void onCompleted(T result);
    public void onLoading(T readedPart, long current, long length);
    public void onInterrupted();
    public void onFail(String errorMsg);
}

小编写的IOUtils工具类,专门用于文件读写,流的读写

public class IOUtils {
    private boolean isRunning = true;

    private long contentLength = 0;
    private String encodeType = "utf-8";

    public IOUtils() {
        isRunning = true;
    }

    public IOUtils setContentLength(long contentLength) {
        this.contentLength = contentLength;
        return this;
    }

    public IOUtils setEncodeType(String encodeType) {
        this.encodeType = encodeType;
        return this;

    }

    public static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void stop() {
        this.isRunning = false;
    }

    public void read(boolean isLine, InputStream inputStream, IOListener ioListener) {
        if (isLine) {
            readLine2String(inputStream, ioListener);
        } else {
            read2String(inputStream, ioListener);

        }
    }

    /**
     * @param ioListener
     */

    public void read2String(String pathFile, IOListener ioListener) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(pathFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
            return;
        }
        read2String(fileInputStream, ioListener);
    }

    public void read2String(InputStream inputStream, IOListener ioListener) {

        if (!(inputStream instanceof BufferedInputStream)) {
            inputStream = new BufferedInputStream(inputStream);
        }
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, encodeType);
            bufferedReader = new BufferedReader(inputStreamReader);

            StringBuilder sb = new StringBuilder();

            char[] buf = new char[1024];
            int len = 0;
            long current = 0;

            while (isRunning && (len = bufferedReader.read(buf)) != -1) {
                sb.append(buf, 0, len);
                current += len;
                ioListener.onLoading("", current, contentLength);
            }

            //中断
            if (len != -1) {
                ioListener.onInterrupted();
            } else {

                ioListener.onCompleted(sb.toString());

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());

        } finally {
            close(bufferedReader);
            close(inputStreamReader);
            close(inputStream);
        }
    }

    /**
     * 同步读取,共享锁,但无法同时进行写操作
     *
     * @param ioListener
     */
    public void read2StrSync(String pathFile, IOListener ioListener) {
        FileInputStream fileInputStream = null;
        FileChannel fileChannel = null;
        FileLock fileLock = null;//文件锁

        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        try {

            /**
             * 读文件
             */

            fileInputStream = new FileInputStream(pathFile);
            fileChannel = fileInputStream.getChannel();
            while (true) {
                try {
                    fileLock = fileChannel.tryLock(0, Long.MAX_VALUE, true);//共享锁
                    break;
                } catch (Exception e) {
                    System.out.println("有其他线程正在操作该文件,当前线程" + Thread.currentThread().getName());
                }
            }
            if (fileLock != null) {

                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int len = 0;
                long current = 0;
                while (isRunning && (len = fileChannel.read(byteBuffer)) != -1) {
                    //0,byteBuffer.position(),必须写这个,否则GG,读取文件错乱
                    byteArrayOutputStream.write(byteBuffer.array(),0,byteBuffer.position());
                    current += len;
                    ioListener.onLoading("", current, fileChannel.size());
                    byteBuffer.clear();
                }
                if (fileLock != null && fileLock.isValid()) {
                LogUtils.log("release-read-lock");
                    fileLock.release();
                }
                close(fileChannel);
                close(fileInputStream);
                //中断
                if (len != -1) {
                    ioListener.onInterrupted();
                } else {
                    ioListener.onCompleted(byteArrayOutputStream.toString("utf-8"));

                }
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());

        } finally {


        }
    }

    /**
     * @param ioListener
     */

    public void readLine2String(String pathFile, IOListener ioListener) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(pathFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
            return;
        }
        readLine2String(fileInputStream, ioListener);
    }

    /**
     * 一行一行地读
     *
     * @param inputStream
     * @param ioListener
     */
    public void readLine2String(InputStream inputStream, IOListener ioListener) {

        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, encodeType);
            bufferedReader = new BufferedReader(inputStreamReader);

            StringBuilder sb = new StringBuilder();
            long current = 0;

            String str;
            while (isRunning && (str = bufferedReader.readLine()) != null) {
                sb.append(str);
                current += str.length();

                ioListener.onLoading(str, current, contentLength);

            }

            //中断
            if ((str = bufferedReader.readLine()) != null) {
                ioListener.onInterrupted();
            } else {

                ioListener.onCompleted(sb.toString());

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());

        } finally {
            close(bufferedReader);
            close(inputStreamReader);
            close(inputStream);
        }
    }

    public void readL2StrNoBuffer(String pathFile, IOListener ioListener) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(pathFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
            return;
        }
        readL2StrNoBuffer(fileInputStream, ioListener);
    }

    /**
     * 一行一行地读,不拼接
     *
     * @param inputStream
     * @param ioListener
     */
    public void readL2StrNoBuffer(InputStream inputStream, IOListener ioListener) {

        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, encodeType);
            bufferedReader = new BufferedReader(inputStreamReader);

            long current = 0;

            String str;
            while (isRunning && (str = bufferedReader.readLine()) != null) {
                current += str.length();

                ioListener.onLoading(str, current, contentLength);

            }

            //中断
            if ((str = bufferedReader.readLine()) != null) {
                ioListener.onInterrupted();
            } else {

                ioListener.onCompleted("");

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());

        } finally {
            close(bufferedReader);
            close(inputStreamReader);
            close(inputStream);
        }
    }

    public void readL_N2String(String pathFile, IOListener ioListener) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(pathFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
            return;
        }
        readL_N2String(fileInputStream, ioListener);
    }

    /**
     * 一行一行地读,\n拼接
     *
     * @param inputStream
     * @param ioListener
     */
    public void readL_N2String(InputStream inputStream, IOListener ioListener) {

        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, encodeType);
            bufferedReader = new BufferedReader(inputStreamReader);

            StringBuilder sb = new StringBuilder();
            long current = 0;

            String str;
            while (isRunning && (str = bufferedReader.readLine()) != null) {
                sb.append(str);
                sb.append("\n");
                current += str.length();

                ioListener.onLoading(str, current, contentLength);

            }

            //中断
            if ((str = bufferedReader.readLine()) != null) {
                ioListener.onInterrupted();
            } else {

                ioListener.onCompleted(sb.toString());

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());

        } finally {
            close(bufferedReader);
            close(inputStreamReader);
            close(inputStream);
        }
    }

    /**
     * 读取到文件
     *
     * @param inputStream
     * @param outputStream
     * @param ioListener
     */
    public void read2File(InputStream inputStream, OutputStream outputStream, IOListener ioListener) {

        try {

            byte[] buffer = new byte[1024];
            int len = 0;
            long current = 0;

            while (isRunning && (len = inputStream.read(buffer)) != -1) {

                outputStream.write(buffer, 0, len);
                current += len;
                ioListener.onLoading(new String(buffer), current, contentLength);
            }

            outputStream.flush();
            //中断
            if (len != -1) {
                ioListener.onInterrupted();
            } else {

                ioListener.onCompleted(null);

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(outputStream);
            close(inputStream);
        }
    }

    /**
     * 将str写入文件
     */
    public void writeStr2File(String str, String pathFile, IOListener ioListener) {
        BufferedWriter bufferedWriter = null;
        OutputStreamWriter outputStreamWriter = null;
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(pathFile);
            outputStreamWriter = new OutputStreamWriter(outputStream);
            bufferedWriter = new BufferedWriter(outputStreamWriter);
            bufferedWriter.write(str);
            ioListener.onCompleted("");
        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
        } finally {
            close(bufferedWriter);
            close(outputStreamWriter);
            close(outputStream);
        }
    }

    /**
     * 将str写入文件,同步操作,独占锁
     */
    public void writeStr2ReplaceFileSync(String str, String pathFile, IOListener ioListener) {
        File file;
        try {
            file = FileUtils.createFile(pathFile);
        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail("文件创建失败,请检查路径是否合法以及读写权限");
            return;
        }
        FileOutputStream fileOutputStream = null;
        FileChannel fileChannel = null;
        FileLock fileLock = null;//文件锁
        try {

            /**
             * 写文件
             */
            fileOutputStream = new FileOutputStream(file);
            fileChannel = fileOutputStream.getChannel();
            while (true) {
                try {
                    fileLock = fileChannel.tryLock();//独占锁
                    break;
                } catch (Exception e) {
                    System.out.println("有其他线程正在操作该文件,当前线程" + Thread.currentThread().getName());
                }
            }
            if (fileLock != null) {
                int len = 0;
                long current = file.length();
                if (isRunning ) {
                    fileChannel.write(ByteBuffer.wrap(str.getBytes()));
                    current += len;
                    LogUtils.log("当前线程" + Thread.currentThread().getName());
                    ioListener.onLoading(str.getBytes(), current, str.length());
                }else {
                    //中断
                    ioListener.onInterrupted();
                }
                if (fileLock != null && fileLock.isValid()) {
                    LogUtils.log("release-write-lock");
                    fileLock.release();
                }
                close(fileChannel);
                close(fileOutputStream);
                if (file.length() == str.getBytes().length) {
                    ioListener.onCompleted(file);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            ioListener.onFail(e.getMessage());
        } finally {
        }
    }

  

}

写文件使用示例

 new IOUtils().writeStr2ReplaceFileSync(jsonObjectOld.toJSONString(), Constants.PATH_GAME_JSON, new IOListener() {
                            @Override
                            public void onCompleted(Object result) {
                                
                            }

                            @Override
                            public void onLoading(Object readedPart, long current, long length) {

                            }

                            @Override
                            public void onInterrupted() {

                            }

                            @Override
                            public void onFail(String errorMsg) {

                            }
                        });

读文件使用示例

new IOUtils().read2StrSync(Constants.PATH_CONFIG_APPLICATION_JSON, new IOListener<String>() {
            @Override
            public void onCompleted(String result) {
                
            }

            @Override
            public void onLoading(String readedPart, long current, long length) {

            }

            @Override
            public void onInterrupted() {

            }

            @Override
            public void onFail(String errorMsg) {

            }
        });

各位老铁有问题欢迎及时联系、指正、批评、撕逼

Github:
https://github.com/AnJiaoDe
简书:
https://www.jianshu.com/u/b8159d455c69

微信公众号

Java NIO 文件通道 FileChannel 用法 阅读详情

相关推荐

STM32F103ZE精英板驱动ESP8266与DHT11构建物联网网关,实现乐联网温湿度数据实时监控

本文详细介绍了如何使用STM32F103ZE精英板驱动ESP8266与DHT11构建物联网网关,实现乐联网温湿度数据实时监控。从硬件选型、连接调试到乐联网平台配置和STM32程序开发,提供了完整的实现步骤和常见问题解决方案,适合物联网入门开发者参考。

weixin_30823001的博客 83

java线程安全问题

当我们使用多个线程访问同一资源(可以是同一个变量、同一个文件、同一条记录等)的时候,若多个线程只有读操作,那么不会发生线程安全问题,但是如果多个线程中对资源有读和写的操作,就容易出现线程安全问题。 1 同一个资源问题 1、局部变量不能共享 public class SaleTicketDemo1 { public static void main(String[] args) { Window w1 = new Window(); Window w2 = ne...

qq_43555873的博客 3820

综合能源系统多时间尺度优化调度!诸多创新点让你抓住审稿人的心!

主要介绍综合能源系统的设备组成结构,并针对屋顶光伏系统、冷-热-电联供系统中的燃气轮机、燃气锅炉、光伏溴化锂制冷机、卡琳娜余热发电、中央空调系统,以及外网交互系统的配电网与天然气管网交互关系进行数学建模。1) 源-荷-储协同调度:研究屋顶光伏、燃气轮机、燃气锅炉等源侧设备,中央空调、电-热-冷负荷、可平移电负荷、可削减温控负荷等负荷侧资源,以及储能系统、电动汽车等储能侧设备的协同调度,以提高风光消纳能力,满足社会能源需求。通过电转热、电转冷、电转气等多能耦合方式,可进一步促进可再生能源的应用与发展。

weixin_48747334的博客 1494

java.nio.channels.FileChannel中lock()与tryLock()方法的区别(Android Studio代码环境)

FileChannel中的lock()与tryLock()方法都是尝试去获取在某一文件上的独有锁(以下简称独有锁),可以实现进程间操作的互斥。区别在于lock()会阻塞(blocking)方法的执行,tryLock()则不会。

leunging的博客 1万+

实时多目标跟踪(MOT):SORT与DeepSORT优化

实时多目标跟踪(MOT):SORT与DeepSORT优化​ ,人工智能,计算机视觉,大模型,AI,本文围绕实时多目标跟踪中的 SORT 与 DeepSORT 算法展开,阐述了两者原理、实现及优化。SORT 结合卡尔曼滤波和匈牙利算法,依赖目标检测,实时性好但复杂场景表现欠佳。DeepSORT 在其基础上引入外观特征,采用级联匹配,提升了跟踪精度和鲁棒性。还探讨了两种算法在检测、运动模型、外观特征等方面的优化方向,以及应用场景与选择建议,为相关应用和研究提供参考。

不踩坑,不知道坑有多深;不总结,踩过的坑白踩。 20万+

黑猫带你学UFS协议第13篇:UFS初始化详解(Boot Operation)

本文详细解析了UFS设备的初始化过程,包括部分初始化、加载启动代码(可选)和初始化完成三个阶段。重点介绍了如何通过设备描述符和逻辑单元描述符配置引导特性,以及如何从UFS设备加载启动代码。内容适用于嵌入式硬件和存储领域的开发者。

黑猫奥利奥的博客 3567

NIO FileChannel中的文件锁lock 学习笔记

NIO FileChannel中的文件锁lock 学习笔记

weixin_46543456的博客 776

1、嵌入式软件系统测试技术解析

本文详细解析了嵌入式软件系统测试的关键技术及其应用,涵盖了从嵌入式系统的背景与特点,到形式化测试技术、实时嵌入式软件测试环境建设,以及Android应用开发测试的多个方面。通过案例分析和测试技术总结,提出了针对不同应用场景的测试策略和建议,并展望了未来测试技术的发展趋势,为提高嵌入式软件的质量和可靠性提供了全面的技术支持。

w8x9y0z1的博客 128

多线程文件锁 java_java多线程读写文件之文件锁

文件修改始终是一件很麻烦也很出错的行为。多线程读写文件更是会加大文件内容混乱的概率,这时,必定要保证在某一个时刻,只有一个线程在对文件进行读写操做。那么其余访问文件的线程该怎么办呢?就像去ATM取钱同样,当ATM正在被使用时,那么其余想要使用ATM的人只能等待知道ATM能使用。java读写文件也同样,当一个线程得到文件时,给予这个线程文件锁。只有拥有文件锁的线程才能操做文件,其余线程就须要一直等待...

weixin_36276256的博客 564

时间序列预测 | 决策树时间序列预测建模,单步、多步(Python)

时间序列预测 | 决策树时间序列预测建模,单步、多步(Python)

天天酷科研的博客 748

YOLOv11缝合添加注意力机制:添加YOLO-Face的SEAM到并行通道空间注意力机制【附代码】

在目标检测的实际应用中,物体遮挡是一个严重影响检测精度的难点。本文将基于YOLOv11架构,探索融合YOLO-Face中提出的SEAM注意力机制以提升对遮挡物体的感知能力,并在此基础上提出一种轻量化双路径并行注意力机制C2PSA,进一步提升检测性能。

一键难忘的博客 1540

Java文件锁以及并发读写中的应用

引言​ 在项目中,如果遇到需要并发读写文件的问题,那么对文件上锁分开访问是十分有必要的。因此这篇博文主要介绍文件锁的相关知识。有误之处,希望指出。什么是文件锁​ 文件锁就如同编程概念中其他锁的意义一样。通过对文件上锁,只有拥有锁的进程才能拥有对应锁权限的操作权限。而没有锁的进程只能挂起或者处理其他的事务直到拥有锁。从而在并发的场景下,我们才能对文件的读写进行控制。分类 共享锁:获取到共享锁,

paditang的博客 1万+

【异常】came as a complete surprise to me,IllegalArgumentException: The template string is not valid.

是Spring AI中用于生成提示词(prompt)的一个类。提示词对于与大语言模型交互至关重要,因为它们指导模型生成特定类型的响应。允许开发者创建包含占位符的模板字符串,并通过提供具体的值来填充这些占位符,从而动态地生成个性化的提示词。

奶爸的编程之路,也就一周冷个三天 752

java 多线程 文件锁

在最近的工作中,经常要用到线程,就对线程相关知识稍微看了看,知道并发线程经常引起共享资源冲突,java以提供关键字synchronized的形式,为防止资源冲突提供了内置支持. 可是在工作中,我却碰到了这样的需求,定时抛出线程读写某文件的内容,由于相隔时间很短,我突然想到,会不会在第二次轮循开始对该文件进行读操作的时候,第一次抛出的线程还在对该文件进行写操作,如果有可能,那么...

javazxc2008的专栏 376

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

【死磕NIO】— 跨进程文件锁:FileLock

大家好,我是大明哥,一个专注于【死磕 Java】系列创作的程序员。 【死磕 Java 】系列为作者「chenssy」 倾情打造的 Java 系列文章,深入分析 Java 相关技术核心原理及源码 死磕 Java :https://www.cmsblogs.com/group/1420041599311810560 上篇文章(【死磕 NIO】— 深入分析Channel和FileChannel)已经详细介绍了 FileChannel的核心原理及相关API,了解了FileChannel是用来读写和映射一个系.

chenssy 的技术博客 3104

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Springboot Java多线程操作本地文件,加读写锁,阻塞的线程等待运行中的线程执行完再查询并写入

在上面的示例中,我们在写线程中使用了独占锁(lock() 方法),在读线程中使用了共享锁(lock(0L, Long.MAX_VALUE, true) 方法)3、性能:在 Java 5 之前,synchronized 的性能比 Lock 要好,但是在 Java 5 之后,Lock 的性能得到了大幅度提升,特别是在高并发的情况下,Lock 的性能优势更加明显。同时,我们还需要在读线程中使用 lock() 方法获取共享锁,这样可以确保读线程在写线程执行完毕后再执行,避免在主线程中,

程序员猫爪 3635

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

FileChannel文件锁

package com.itbuluoge.nio; import java.io.FileOutputStream; import java.nio.channels.FileLock; public class FileChannel { /** * @param args * @throws Exception */ public static void main(S

jianghuihong2012的专栏 1456

多线程文件锁 java_Java NIO中的FileLock(文件锁)

FileLock,文件锁。文件锁在OS中很常见,如果多个程序同时访问、修改同一个文件,很容易因为文件数据不同步而出现问题。给文件加一个锁,同一时间,只能有一个程序修改此文件,或者程序都只能读此文件,这就解决了同步问题,保证了线程安全。文件锁是进程级别的,不是线程级别的。文件锁可以解决多个进程并发访问、修改同一个文件的问题,但不能解决多线程并发访问、修改同一文件的问题。就是说使用文件锁时,同一进程内...

weixin_42519826的博客 521

【Java NIO】— 跨进程文件锁:FileLock

作者简介:大家好,我是码炫码哥,前中兴通讯、美团架构师,现任某互联网公司CTO,兼职码炫课堂主讲源码系列专题代表作:《jdk源码&多线程&高并发》,《深入tomcat源码解析》,《深入netty源码解析》,《深入dubbo源码解析》,《深入springboot源码解析》,《深入spring源码解析》,《深入redis源码解析》等联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬。

smart_an的专栏 1179

Java 文件锁的使用

多线程-内部锁、重进入 多线程         java提供了强制原子性的内部锁机制:synchronized块。一个synchronized块有两个部分:锁对象的引用和锁保护的代码块。synchronized方法上面的锁也分两种:对象锁和类锁。当该方法为static方法时,该方法获取到的锁为该Class对象锁。 重进入?           当某个线程进入A方法的时候获取...

topMan'blog 312

多线程文件锁 java_Java处理多人同时读写文件的文件锁处理

最近项目中有遇到并发同时访问一个文件读写的情况、但是同时读写就会出错、所以我研究了一下java文件锁这个机制下面直接贴代码我通过的是线程来模拟多人同时读写的情况写文件1 packagecom.dnion.test;23 importjava.io.File;4 importjava.io.IOException;5 importjava.io.RandomAccessFile;6 importja...

weixin_42300211的博客 413

java:随机流(RandomAccessFile+ FileChannel+ FileLock)

import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.util.Scanner; public class Test {...

weixin_44001521的博客 1239

java实现文件锁(附带源码)

java实现文件锁(附带源码)

欢迎来到我的博客!这里是一个专注于计算机技术的分享平台,涵盖编程开发、算法研究、系统架构、软件工程等多个领域。无论你是初学者还是资深开发者,都能在这里找到有价值的内容。 1236
上一篇: ./bin/flink run -p 10 ../examples/*WordCount-java*.jar 提交方式
下一篇: HTTP API接口安全设计
王树民
博客等级 码龄10年 912粉丝 560原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址