简体   繁体   中英

Operating System event handler using Java

I have a java process which working as a daemon, it monitor a directroy on the file system,once a newy file is added to the directory the java process will handle this file by perform some logic on it, currently in my implementaion the daemon check the folder each 10 seconds and in case new file is added it will start to handle it.

is there a way that the folder will notify to the process that new file is added, and then the process can start to work on it, kind of event handler on the folder it self is the OS level by java API, can i do this in java?

There is no way that I know of. Anyway, for the folder notifying something, you would probably have to change (create your own) filesystem driver.

A system event is very OS dependant, and Java is designed to be the opposite.

It depends how fast do you want your daemon to respond. Using the sleep method, you cand shorten the sleep time, but it will use more CPU cycles.

For now you can use an existing utility like jfilenotify , but it is coming as one of the new features in Java 7 .

You should design your code such that the notify mechanism is decoupled from your handler, thus allowing you to easily upgrade.

I think a problem you'll run into is concurrent access to the same file. If it's still being written, then you can't get exclusive access to the file.. and there's no gaurentee that the file even has any data yet. You can probably (ab)use that fact to see if in fact the file is actually done.

Attempt to get an exclusive lock on that file and if that fails, that mean the file isn't done being written to. Once it has an exclusive lock, then the file is likely to be done and you can process it as you please.

Look at java.nio.channels.FileLock and see if that will work for you. ( http://download.oracle.com/javase/6/docs/api/java/nio/channels/FileLock.html )

If you're using Java 7 try reading this . There's a WatchService class that may handle what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM