How to use mkdirs in a thread safe manner in Java?

前端 未结 5 2278
执念已碎
执念已碎 2021-02-14 17:51

After experiencing issues with mkdirs() and poking around the interwebs, I get the impression that there are thread safety issues with mkdirs().

Is there a way to ensure

5条回答
  •  梦毁少年i
    2021-02-14 18:48

    One possible solution would be a MkDirService (illustrated below) that guarantees only one instance and runs in it's own thread. Making use of BlockingQueue.

    First the Service:

    package mkdir;
    
    import java.io.File;
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.LinkedBlockingQueue;
    
    public class MkDirService extends Thread {
    
        private static MkDirService service;
        private BlockingQueue pendingDirs = new LinkedBlockingQueue();
        private boolean run = true;
    
        private MkDirService() {
        }
    
        public synchronized static MkDirService getService() {
            if (service == null) {
                service = new MkDirService();
                new Thread(service).start();
            }
            return service;
        }
    
        public void makeDir(File dir) {
            pendingDirs.add(dir);
        }
    
        public void shutdown() {
            run = false;
        }
    
        @Override
        public void run() {
            while (run || !pendingDirs.isEmpty()) {
                File curDir = null;
                try {
                    curDir = pendingDirs.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (curDir != null && !curDir.exists()) {
                    curDir.mkdir();
                    System.out.println("Made: " + curDir.getAbsolutePath());
                }
            }
        }
    }
    

    The the Test:

    package mkdir;
    
    import java.io.File;
    
    public class MkDirServiceTest {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            MkDirService mdServ = MkDirService.getService();
            mdServ.makeDir(new File("test1"));
            mdServ.makeDir(new File("test1/test2"));
            mdServ.makeDir(new File("test1/test3"));
            mdServ.shutdown();
    
        }
    }
    

提交回复
热议问题