java - 加速 Java 应用程序

标签 java multithreading

我的应用程序监听某个目录及其子目录。为了监听目录,我使用 JNotify 。当在目录上创建新文件时,应用程序会检查文件并以某种方式处理它。下面是代码:

import net.contentobjects.jnotify.JNotify;
import net.contentobjects.jnotify.JNotifyListener;

    public class JNotifyDemo {

    public void sample() throws Exception {
        // path to watch
        //String path = System.getProperty("user.home");
        String path = "/folder";
        System.out.println(path);

        // watch mask, specify events you care about,
        // or JNotify.FILE_ANY for all events.
        int mask = JNotify.FILE_CREATED
                | JNotify.FILE_DELETED
                | JNotify.FILE_MODIFIED
                | JNotify.FILE_RENAMED;

        // watch subtree?
        boolean watchSubtree = true;

        // add actual watch
        int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());

        // sleep a little, the application will exit if you
        // don't (watching is asynchronous), depending on your
        // application, this may not be required
        Thread.sleep(1000000);

        // to remove watch the watch
        boolean res = JNotify.removeWatch(watchID);
        if (!res) {
            // invalid watch ID specified.
        }
    }

    class Listener implements JNotifyListener {

        public void fileRenamed(int wd, String rootPath, String oldName,
                String newName) {
            print("renamed " + rootPath + " : " + oldName + " -> " + newName);
        }

        public void fileModified(int wd, String rootPath, String name) {
            print("modified " + rootPath + " : " + name);
        }

        public void fileDeleted(int wd, String rootPath, String name) {
            print("deleted " + rootPath + " : " + name);
        }

        public void fileCreated(int wd, String rootPath, String name) {
            print("created " + rootPath + " : " + name);
            //check file whether it is xml or not
            //validate xml
            //do some internal processing of file
            // and do other jobs like inserting into database
        }

        void print(String msg) {
            System.err.println(msg);
        }
    }

    public static void main(String[] args) throws Exception {
        new JNotifyDemo().sample();
    }
}

从代码中可以看出,应用程序每次处理一个文件。有什么建议可以加快此应用程序的速度,例如使用线程或其他任何东西吗?

最佳答案

我建议您使用java.nio.file.Path,它扩展了Watchable接口(interface),它可以注册到 watch 服务,以便可以观看它用于更改和事件。

这种事件驱动的方法可以加快您的应用程序的速度。看看example .

PathWatchable 均包含在 java 7 中。

关于java - 加速 Java 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13875277/

相关文章:

ios - Swift 4 - 在我的 RESTful API 调用中是 "Background Thread?"

Java 正在分配额外的 2gb 内存

java - 避免 JSP 和 HTML 标记语法模糊(<、/和 > 字符)的方法?

java - JFrame 内的 JPanel 背景颜色不起作用

java - 将线程与 paint java 一起使用

java - 当我尝试倒计时时同步被阻塞

c - 函数 pthread_yield 是如何工作的?

c# - 在 C# 中将 'using' 与线程实用程序一起使用 - 何时调用 Dispose?

java - 短字符串的哈希码可以相同吗?

java - 如何在 java 中将 JSONObject 转换为 DefaultMutableTreeNode?