In a WatchService, what happens between key.pollEvents() and key.reset()?

谁说我不能喝 提交于 2019-12-10 19:02:05

问题


Looking at this Java example, about the key state, Oracle says:

Ready indicates that the key is ready to accept events. When first created, a key is in the ready state.

Signaled indicates that one or more events are queued. Once the key has been signaled, it is no longer in the ready state until the reset method is invoked.

In WatchKey javadoc:

Events detected while the key is in the signaled state are queued but do not cause the key to be re-queued for retrieval from the watch service

The documentation doesn't say what happens to events generated between key.pollEvents() and key.reset()? It is assumed that events will be buffered until the key is reset, and the key will be signaled immediately after the reset. This seems supported by the test below.

Could you point me to some official documentation? or to a discussion about the lack of documentation?


Path dir = Paths.get("test");
WatchService watcher = dir.getFileSystem().newWatchService();
dir.register(watcher, CREATE, DELETE, MODIFY);
while (true) {
    WatchKey key = watcher.take();
    System.out.println("polling.");
    for (WatchEvent<?> event : key.pollEvents()) {
        ... (details removed) ...
        System.out.format("  Event %s in [%s] for entry [%s]%n",
                          event.kind().name(), registeredDir, childPath);
        try { Thread.sleep(20000); } catch (InterruptedException e) { ; }
    }
    System.out.println("resetting.");
    key.reset();
}

... within the 20s allowed by the sleep(), I did:

  • Create a file,
  • Edit it, save it,
  • Rename it,
  • Edit it, save it,
  • Delete it

Output:

polling.
  Event ENTRY_CREATE in [test] for entry [test\file1.txt]
resetting.
polling.
  Event ENTRY_MODIFY in [test] for entry [test\file1.txt]
  Event ENTRY_DELETE in [test] for entry [test\file1.txt]
  Event ENTRY_CREATE in [test] for entry [test\file2.txt]
  Event ENTRY_MODIFY in [test] for entry [test\file2.txt]
  Event ENTRY_DELETE in [test] for entry [test\file2.txt]
resetting.

Tks.


回答1:


It looks like additional events are buffered and will be processed or given the event type of OVERFLOW when the buffer fills up.

from the documentation for watchservice :

"File systems may report events faster than they can be retrieved or processed and an implementation may impose an unspecified limit on the number of events that it may accumulate. Where an implementation knowingly discards events then it arranges for the key's pollEvents method to return an element with an event type of OVERFLOW. This event can be used by the consumer as a trigger to re-examine the state of the object."



来源:https://stackoverflow.com/questions/24342216/in-a-watchservice-what-happens-between-key-pollevents-and-key-reset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!