Concurrent and Blocking Queue in Java

后端 未结 6 2057
一生所求
一生所求 2020-12-12 18:42

I have the classic problem of a thread pushing events to the incoming queue of a second thread. Only this time, I am very interested about performance. What I want to achiev

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 18:54

    Similar to this answer https://stackoverflow.com/a/1212515/1102730 but a bit different.. I ended up using an ExecutorService. You can instantiate one by using Executors.newSingleThreadExecutor(). I needed a concurrent queue for reading/writing BufferedImages to files, as well as atomicity with reads and writes. I only need a single thread because the file IO is orders of magnitude faster than the source, net IO. Also, I was more concerned about atomicity of actions and correctness than performance, but this approach can also be done with multiple threads in the pool to speed things up.

    To get an image (Try-Catch-Finally omitted):

    Future futureImage = executorService.submit(new Callable() {
        @Override
            public BufferedImage call() throws Exception {
                ImageInputStream is = new FileImageInputStream(file);
                return  ImageIO.read(is);
            }
        })
    
    image = futureImage.get();
    

    To save an image (Try-Catch-Finally omitted):

    Future futureWrite = executorService.submit(new Callable() {
        @Override
        public Boolean call() {
            FileOutputStream os = new FileOutputStream(file); 
            return ImageIO.write(image, getFileFormat(), os);  
        }
    });
    
    boolean wasWritten = futureWrite.get();
    

    It's important to note that you should flush and close your streams in a finally block. I don't know about how it performs compared to other solutions, but it is pretty versatile.

提交回复
热议问题