2012-12-14 49 views
0

我的應用程序偵聽某個目錄,它是子目錄。爲了收聽目錄我使用JNotify。在目錄應用程序上創建新文件時,會檢查文件並以某種方式處理它。以下是代碼:加速Java應用程序

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(); 
    } 
} 

正如您從代碼中看到的,應用程序每次處理一個文件。任何建議加快這個應用程序就像使用線程或其他任何東西?

+0

什麼需要加快?在知道它是否應該優化之前不要進行優化,以及應該優化哪些內容。 –

+0

我在這裏看不到任何瓶頸,因爲你沒有對你的代碼做任何事情。它只是演示中的一個觀察者代碼。 – gigadot

+1

也許'同步打印'?然後推遲消息隊列。 –

回答

1

我想催促您使用java.nio.file.Path,它擴展了Watchable界面,它可以註冊到監視服務,以便可以監視變化和事件。

這種事件驅動的方法加快了您的應用程序。看一下example

PathWatchable都包含在Java 7中

+0

java 7中的觀察者服務存在很多問題,例如http://stackoverflow.com/questions/8109382/java-nio-filesystem-watcher-locks-directories-deletion-becomes-impossible – gigadot

0

實際上有多少處理回事?請記住,IO非常慢,除非您的處理需要大量時間,否則多線程解決方案將成爲讀取文件的瓶頸。

反正,實現並行處理的快捷方式是啓動ExecutorService並提交一個Runnable文件路徑作爲參數。