[英]Speeding up Java application
我的应用程序侦听某个目录及其子目录。 为了侦听目录,我使用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();
}
}
从代码中可以看到,应用程序每次处理一个文件。 有什么建议可以像使用线程或其他任何方式来加速此应用程序吗?
我建议您使用扩展Watchable
接口的java.nio.file.Path
,它可以在watch服务中注册,以便可以监视其更改和事件。
这种事件驱动的方法可以加速您的应用程序。 看个例子 。
Path
和Watchable
都包含在Java 7中。
实际正在进行多少处理? 请记住,IO非常慢,并且,除非您的处理花费大量时间,否则多线程解决方案将成为读取文件的瓶颈。
无论如何,实现并行处理的快速方法是启动ExecutorService并将其提交为带有文件路径作为参数的Runnable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.