Watch Service Java - 后台中的两个并行线程

时间:2016-05-25 19:49:50

标签: java multithreading thread-safety servletcontextlistener

我需要在Web应用程序的两个目录中监视更改(上载的文件)。我创建了一个ServletContextListener来触发对这两个目录的监视。

我的问题是,当第一次监控开始时,线程被阻塞,第二次监控没有启动。

是否可以保持两个不同文件夹的监控并行和后台运行?

我知道问题是由于无限循环,但不知道如何将此线程放在后台。任何帮助将不胜感激 。非常感谢您提前

ContextListener

@Override
    public void contextInitialized(ServletContextEvent event) {

        Path pathFolder1 = Paths.get("my_folder_1_path");
        MyWatcher watcher1 = new MyWatcher();

        Path pathFolder2 = Paths.get("my_folder_2_path");
        MyWatcher watcher2 = new MyWatcher();

        watcher1.startMonitoring(pathFolder1);
        watcher2.startMonitoring(pathFolder2);
    }

MyWatcher

public void startMonitoring(Path directory) {

        try {
            FileSystem fs = directory.getFileSystem ();
            WatchService watcher = fs.newWatchService();

            while(true) {

                directory.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
                WatchKey watckKey = watcher.take();
                List<WatchEvent<?>> events = watckKey.pollEvents();

                for (WatchEvent event : events) {

                    if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println("File created: " + event.context().toString());
                    }
                    if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                        System.out.println("File removed: " + event.context().toString());
                    }
                }
                watckKey.reset();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

1 个答案:

答案 0 :(得分:1)

您应该在应用服务器上配置线程工厂,通过@Resource注释注入它,并使用那里的线程。一个谷歌搜索的例子是a blog entry about this