开发者

Adding return statement to watchable in Java

How to add return statement to watchable method in Java and still be working properly. I want always to be searching for files, OK I have that. But now I want to get the return, but when I add return statement everything goes down the function stops and the watchable stops too .. Any ideas ?

for (;;) {
    WatchKey key = watcher.take();
    for (WatchEvent<?> event: key.pollEvents()) {
        if (event.kind() == StandardWatchEventKind.ENTRY_CREATE) {
            System.out.println(event.context().toString());
    }
}

Here is the loop wh开发者_StackOverflowich always searches, how to return from It and still to be working?


I think you mean you want to perform other actions in the program, while still having the watcher run. For that, you would need to create and start a new Thread for the watcher:

Thread watcherThread = new Thread(new Runnable() {
    public void run() {
        // Watcher loop code goes here
    }
});
watcherThread.start();


As @dlev says, if you want your application to process watch events at the same time as it is doing other things, then the way to do it is in a separate thread.

This leaves you with the problem of "returning" the information. (I presume that simply printing the information to standard output is not any use to you.)

As you observed, you can't use return because that will terminate the loop.

The basic answer is that you need to put the information somewhere so that the rest of your application can access. For example:

  • You could create a queue object (e.g. a ConcurrentLinkedQueue), have your watcher enqueue the data, and have some other thread dequeue it and process it.

  • You could have the watcher process the event payload itself and put the results into a shared data structure.

However, without more information, it is difficult to decide what approach will be best for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜