Class ResourceWatcher
java.lang.Object
cloud.opencode.base.classloader.resource.ResourceWatcher
- All Implemented Interfaces:
AutoCloseable
Resource Watcher - Watches file resources for changes using WatchService
资源监听器 - 使用 WatchService 监听文件资源变更
Monitors file system paths for create, modify, and delete events. Uses a virtual thread daemon for the poll loop and provides debouncing to coalesce rapid successive events on the same file.
监视文件系统路径的创建、修改和删除事件。使用虚拟线程守护进程进行轮询循环, 并提供去抖动功能以合并同一文件上快速连续的事件。
Features | 主要功能:
- Watch individual files - 监听单个文件
- Watch directories with glob patterns - 使用 glob 模式监听目录
- Debouncing (100ms window) - 去抖动(100ms 窗口)
- Virtual thread poll loop - 虚拟线程轮询循环
Usage Examples | 使用示例:
try (ResourceWatcher watcher = new ResourceWatcher()) {
ResourceWatchHandle handle = watcher.watch(Path.of("config.yml"), event -> {
System.out.println(event.type() + ": " + event.resource().getFilename());
});
// ... later
handle.close(); // stop watching
}
Security | 安全性:
- Thread-safe: Yes - 线程安全: 是
- Null-safe: Yes - 空值安全: 是
- Since:
- JDK 25, opencode-base-classloader V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Close the watcher, stopping the poll loop and releasing all resources 关闭监听器,停止轮询循环并释放所有资源intGet number of active watches 获取活跃监听数量watch(Path filePath, Consumer<ResourceEvent> callback) Watch a file path for changes 监听文件路径的变更watchPattern(Path directory, String globPattern, Consumer<ResourceEvent> callback) Watch a directory for changes matching a glob pattern 监听目录中匹配 glob 模式的变更
-
Constructor Details
-
ResourceWatcher
Create a new ResourceWatcher 创建新的 ResourceWatcher- Throws:
IOException- if cannot create WatchService | 无法创建 WatchService 时抛出
-
-
Method Details
-
watch
Watch a file path for changes 监听文件路径的变更- Parameters:
filePath- path to watch | 要监听的文件路径callback- event callback | 事件回调- Returns:
- closeable handle | 可关闭的句柄
- Throws:
NullPointerException- if filePath or callback is null | 如果 filePath 或 callback 为 null 则抛出
-
watchPattern
public ResourceWatchHandle watchPattern(Path directory, String globPattern, Consumer<ResourceEvent> callback) Watch a directory for changes matching a glob pattern 监听目录中匹配 glob 模式的变更- Parameters:
directory- directory to watch | 要监听的目录globPattern- glob pattern (e.g. "*.yml") | glob 模式(如 "*.yml")callback- event callback | 事件回调- Returns:
- closeable handle | 可关闭的句柄
- Throws:
NullPointerException- if any argument is null | 如果任何参数为 null 则抛出
-
getWatchCount
public int getWatchCount()Get number of active watches 获取活跃监听数量- Returns:
- number of active watches | 活跃监听数量
-
close
Close the watcher, stopping the poll loop and releasing all resources 关闭监听器,停止轮询循环并释放所有资源- Specified by:
closein interfaceAutoCloseable- Throws:
IOException- if closing fails | 关闭失败时抛出
-