WatchKey
Stay organized with collections
Save and categorize content based on your preferences.
A token representing the registration of a watchable
object
with a WatchService
.
A watch key is created when a watchable object is registered with a watch
service. The key remains valid
until:
- It is cancelled, explicitly, by invoking its
cancel
method, or
- Cancelled implicitly, because the object is no longer accessible,
or
- By
closing
the watch service.
A watch key has a state. When initially created the key is said to be
ready. When an event is detected then the key is signalled
and queued so that it can be retrieved by invoking the watch service's poll
or take
methods. Once
signalled, a key remains in this state until its reset
method
is invoked to return the key to the ready state. Events detected while the
key is in the signalled state are queued but do not cause the key to be
re-queued for retrieval from the watch service. Events are retrieved by
invoking the key's pollEvents
method. This method
retrieves and removes all events accumulated for the object. When initially
created, a watch key has no pending events. Typically events are retrieved
when the key is in the signalled state leading to the following idiom:
for (;;) {
// retrieve key
WatchKey key = watcher.take();
// process events
for (WatchEvent<?> event: key.pollEvents()) {
:
}
// reset the key
boolean valid = key.reset();
if (!valid) {
// object no longer registered
}
}
Watch keys are safe for use by multiple concurrent threads. Where there
are several threads retrieving signalled keys from a watch service then care
should be taken to ensure that the reset
method is only invoked after
the events for the object have been processed. This ensures that one thread
is processing the events for an object at any time.
Public Method Summary
abstract
void
|
cancel()
Cancels the registration with the watch service.
|
abstract
boolean
|
isValid()
Tells whether or not this watch key is valid.
|
abstract
List<WatchEvent<?>>
|
pollEvents()
Retrieves and removes all pending events for this watch key, returning
a List of the events that were retrieved.
|
abstract
boolean
|
reset()
Resets this watch key.
|
abstract
Watchable
|
watchable()
Returns the object for which this watch key was created.
|
Public Methods
public
abstract
void
cancel
()
Cancels the registration with the watch service. Upon return the watch key
will be invalid. If the watch key is enqueued, waiting to be retrieved
from the watch service, then it will remain in the queue until it is
removed. Pending events, if any, remain pending and may be retrieved by
invoking the pollEvents
method after the key is
cancelled.
If this watch key has already been cancelled then invoking this
method has no effect. Once cancelled, a watch key remains forever invalid.
public
abstract
boolean
isValid
()
Tells whether or not this watch key is valid.
A watch key is valid upon creation and remains until it is cancelled,
or its watch service is closed.
Returns
true
if, and only if, this watch key is valid
public
abstract
List<WatchEvent<?>>
pollEvents
()
Retrieves and removes all pending events for this watch key, returning
a List
of the events that were retrieved.
Note that this method does not wait if there are no events pending.
Returns
- the list of the events retrieved; may be empty
public
abstract
boolean
reset
()
Resets this watch key.
If this watch key has been cancelled or this watch key is already in
the ready state then invoking this method has no effect. Otherwise
if there are pending events for the object then this watch key is
immediately re-queued to the watch service. If there are no pending
events then the watch key is put into the ready state and will remain in
that state until an event is detected or the watch key is cancelled.
Returns
true
if the watch key is valid and has been reset, and
false
if the watch key could not be reset because it is
no longer valid
public
abstract
Watchable
watchable
()
Returns the object for which this watch key was created. This method will
continue to return the object even after the key is cancelled.
As the WatchService
is intended to map directly on to the
native file event notification facility (where available) then many of
details on how registered objects are watched is highly implementation
specific. When watching a directory for changes for example, and the
directory is moved or renamed in the file system, there is no guarantee
that the watch key will be cancelled and so the object returned by this
method may no longer be a valid path to the directory.
Returns
- the object for which this watch key was created
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2024-07-10 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-07-10 UTC."],[[["\u003cp\u003eA \u003ccode\u003eWatchKey\u003c/code\u003e represents the registration of an object with a \u003ccode\u003eWatchService\u003c/code\u003e for monitoring events like file system changes.\u003c/p\u003e\n"],["\u003cp\u003eIt becomes invalid when cancelled explicitly, implicitly due to object inaccessibility, or when the watch service is closed.\u003c/p\u003e\n"],["\u003cp\u003eEvents are retrieved using \u003ccode\u003epollEvents()\u003c/code\u003e after the key is signaled, indicating an event has occurred.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003ereset()\u003c/code\u003e method returns the key to the ready state for receiving further events, and it should be invoked after event processing.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eWatchKey\u003c/code\u003e is thread-safe, but caution is needed when multiple threads access it, ensuring \u003ccode\u003ereset()\u003c/code\u003e is called only after processing all events for an object.\u003c/p\u003e\n"]]],["A `WatchKey` represents a registration with a `WatchService`. It's created upon registration and remains valid until explicitly canceled via `cancel()`, implicitly canceled, or the service is closed. A key can be *ready* or *signaled*. Events are detected, key is signaled, events are queued. `pollEvents()` retrieves queued events. `reset()` returns the key to *ready* if valid. `isValid()` checks validity, `watchable()` returns the associated object. These operations are thread-safe.\n"],null,["# WatchKey\n\npublic interface **WatchKey** \nA token representing the registration of a [watchable](../../../../reference/java/nio/file/Watchable.html) object\nwith a [WatchService](../../../../reference/java/nio/file/WatchService.html).\n\nA watch key is created when a watchable object is registered with a watch\nservice. The key remains [valid](../../../../reference/java/nio/file/WatchKey.html#isValid()) until:\n\n1. It is cancelled, explicitly, by invoking its [cancel](../../../../reference/java/nio/file/WatchKey.html#cancel()) method, or\n2. Cancelled implicitly, because the object is no longer accessible, or\n3. By [closing](../../../../reference/java/nio/file/WatchService.html#close()) the watch service.\n\nA watch key has a state. When initially created the key is said to be\n*ready* . When an event is detected then the key is *signalled*\nand queued so that it can be retrieved by invoking the watch service's [poll](../../../../reference/java/nio/file/WatchService.html#poll()) or [take](../../../../reference/java/nio/file/WatchService.html#take()) methods. Once\nsignalled, a key remains in this state until its [reset](../../../../reference/java/nio/file/WatchKey.html#reset()) method\nis invoked to return the key to the ready state. Events detected while the\nkey is in the signalled state are queued but do not cause the key to be\nre-queued for retrieval from the watch service. Events are retrieved by\ninvoking the key's [pollEvents](../../../../reference/java/nio/file/WatchKey.html#pollEvents()) method. This method\nretrieves and removes all events accumulated for the object. When initially\ncreated, a watch key has no pending events. Typically events are retrieved\nwhen the key is in the signalled state leading to the following idiom:\n\n```\n for (;;) {\n // retrieve key\n WatchKey key = watcher.take();\n\n // process events\n for (WatchEvent\u003c?\u003e event: key.pollEvents()) {\n :\n }\n\n // reset the key\n boolean valid = key.reset();\n if (!valid) {\n // object no longer registered\n }\n }\n \n```\n\nWatch keys are safe for use by multiple concurrent threads. Where there\nare several threads retrieving signalled keys from a watch service then care\nshould be taken to ensure that the `reset` method is only invoked after\nthe events for the object have been processed. This ensures that one thread\nis processing the events for an object at any time. \n\n### Public Method Summary\n\n|--------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| abstract void | [cancel](../../../../reference/java/nio/file/WatchKey.html#cancel())() Cancels the registration with the watch service. |\n| abstract boolean | [isValid](../../../../reference/java/nio/file/WatchKey.html#isValid())() Tells whether or not this watch key is valid. |\n| abstract [List](../../../../reference/java/util/List.html)\\\u003c[WatchEvent](../../../../reference/java/nio/file/WatchEvent.html)\\\u003c?\\\u003e\\\u003e | [pollEvents](../../../../reference/java/nio/file/WatchKey.html#pollEvents())() Retrieves and removes all pending events for this watch key, returning a `List` of the events that were retrieved. |\n| abstract boolean | [reset](../../../../reference/java/nio/file/WatchKey.html#reset())() Resets this watch key. |\n| abstract [Watchable](../../../../reference/java/nio/file/Watchable.html) | [watchable](../../../../reference/java/nio/file/WatchKey.html#watchable())() Returns the object for which this watch key was created. |\n\nPublic Methods\n--------------\n\n#### public abstract void\n**cancel**\n()\n\nCancels the registration with the watch service. Upon return the watch key\nwill be invalid. If the watch key is enqueued, waiting to be retrieved\nfrom the watch service, then it will remain in the queue until it is\nremoved. Pending events, if any, remain pending and may be retrieved by\ninvoking the [pollEvents](../../../../reference/java/nio/file/WatchKey.html#pollEvents()) method after the key is\ncancelled.\n\nIf this watch key has already been cancelled then invoking this\nmethod has no effect. Once cancelled, a watch key remains forever invalid. \n\n#### public abstract boolean\n**isValid**\n()\n\nTells whether or not this watch key is valid.\n\nA watch key is valid upon creation and remains until it is cancelled,\nor its watch service is closed. \n\n##### Returns\n\n- `true` if, and only if, this watch key is valid \n\n#### public abstract [List](../../../../reference/java/util/List.html)\\\u003c[WatchEvent](../../../../reference/java/nio/file/WatchEvent.html)\\\u003c?\\\u003e\\\u003e\n**pollEvents**\n()\n\nRetrieves and removes all pending events for this watch key, returning\na `List` of the events that were retrieved.\n\nNote that this method does not wait if there are no events pending. \n\n##### Returns\n\n- the list of the events retrieved; may be empty \n\n#### public abstract boolean\n**reset**\n()\n\nResets this watch key.\n\nIf this watch key has been cancelled or this watch key is already in\nthe ready state then invoking this method has no effect. Otherwise\nif there are pending events for the object then this watch key is\nimmediately re-queued to the watch service. If there are no pending\nevents then the watch key is put into the ready state and will remain in\nthat state until an event is detected or the watch key is cancelled. \n\n##### Returns\n\n- `true` if the watch key is valid and has been reset, and `false` if the watch key could not be reset because it is no longer [valid](../../../../reference/java/nio/file/WatchKey.html#isValid()) \n\n#### public abstract [Watchable](../../../../reference/java/nio/file/Watchable.html)\n**watchable**\n()\n\nReturns the object for which this watch key was created. This method will\ncontinue to return the object even after the key is cancelled.\n\nAs the `WatchService` is intended to map directly on to the\nnative file event notification facility (where available) then many of\ndetails on how registered objects are watched is highly implementation\nspecific. When watching a directory for changes for example, and the\ndirectory is moved or renamed in the file system, there is no guarantee\nthat the watch key will be cancelled and so the object returned by this\nmethod may no longer be a valid path to the directory. \n\n##### Returns\n\n- the object for which this watch key was created"]]