JDK 之 NIO 2 WatchService、WatchKey(监控文件变化)
JDK 之 NIO 2 WatchService、WatchKey(监控文件变化)
JDK 规范目录(https://www.cnblogs.com/binarylei/p/10200503.html)
一、WatchService、WatchKey 使用
具体详见:https://blog.csdn.net/lirx_tech/article/details/51425364
public static void main(String[] args) throws Exception {
// 1. 获取文件系统监控器,启动一个后台线程轮询
WatchService watchService = FileSystems.getDefault().newWatchService();
// 2. 注册要监听的事件类型,文件增、删、改
Paths.get("C:\\Users\\len\\Desktop\\xdr").register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
// 3. 获取准备好的事件,pool() 立即返回、take() 阻塞
WatchKey watchKey = watchService.poll(2, TimeUnit.SECONDS);
if (Objects.isNull(watchKey)) {
continue;
}
// 4. 处理准备好的事件
List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
for (WatchEvent<?> event : watchEvents) {
if (event.kind().name().equals(StandardWatchEventKinds.ENTRY_CREATE.name())) {
System.out.println("create: " + event.context());
} else if (event.kind().name().equals(StandardWatchEventKinds.ENTRY_MODIFY.name())) {
System.out.println("modify: " + event.context());
} else if (event.kind().name().equals(StandardWatchEventKinds.ENTRY_DELETE.name())) {
System.out.println("delete: " + event.context());
}
}
// 5. 重启该线程,因为处理文件可能是一个耗时的过程,因此调用 pool() 时需要阻塞监控器线程
boolean valid = watchKey.reset();
if (!valid) {
break;
}
}
}
二、原理

AbstractWatchService实现 WatchService 接口WindowsWatchService具体的实现,启动 Poller 线程Poller线程,轮询指定的目录
(1) AbstractWatchService
// 等待要处理的事件 signaled keys waiting to be dequeued
private final LinkedBlockingDeque<WatchKey> pendingKeys = new LinkedBlockingDeque<WatchKey>();
@Override
public final WatchKey poll(long timeout, TimeUnit unit) throws InterruptedException {
checkOpen();
WatchKey key = pendingKeys.poll(timeout, unit);
checkKey(key);
return key;
}
可以看到调用 poll 的时候直接从队列中取 key,那就必然有一个线程往 pendingKeys 中塞数据。在 AbstractWatchService 中有一个 enqueueKey 方法往 pendingKeys 中塞数据。
final void enqueueKey(WatchKey key) {
pendingKeys.offer(key);
}
(2) WindowsWatchService
AbstractWatchService 有不同的实现,以 WindowsWatchService 为例。
WindowsWatchService(WindowsFileSystem fs) throws IOException {
// create I/O completion port
long port = 0L;
try {
port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0);
} catch (WindowsException x) {
throw new IOException(x.getMessage());
}
this.poller = new Poller(fs, this, port);
this.poller.start();
}
Poller 是 WindowsWatchService 的内部类,开启了一个线程监控目录。
(3) Poller
重点关注 Poller 中的 run 方法。
@Override
public void run() {
for (;;) {
CompletionStatus info;
try {
info = GetQueuedCompletionStatus(port);
} catch (WindowsException x) {
return;
}
WindowsWatchKey key = ck2key.get((int)info.completionKey());
if (key == null) {
continue;
}
boolean criticalError = false;
if (errorCode == ERROR_NOTIFY_ENUM_DIR) {
key.signalEvent(StandardWatchEventKinds.OVERFLOW, null);
} else if (errorCode != 0 && errorCode != ERROR_MORE_DATA) {
criticalError = true;
} else {
// 省略... (处理 error)
}
// 一切正常则 criticalError = true,此时将这个 WatchKey 加入 pendingKeys 中
if (criticalError) {
implCancelKey(key);
key.signal();
}
}
}
参考:
- 《NIO.2:WatchService、WatchKey(监控文件变化)》:(https://blog.csdn.net/lirx_tech/article/details/51425364)
每天用心记录一点点。内容也许不重要,但习惯很重要!
JDK 之 NIO 2 WatchService、WatchKey(监控文件变化)的更多相关文章
- 利用WatchService监听文件变化
在实现配置中心的多种方案中,有基于JDK7+的WatchService方法,其在单机应用中还是挺有实践的意义的. 代码如下: package com.longge.mytest; import jav ...
- Python监控文件变化:watchdog
Python监控文件变化有两种库:pyinotify和watchdog.pyinotify依赖于Linux平台的inotify,后者则对不同平台的的事件都进行了封装.也就是说,watchdog跨平台. ...
- mac 监控文件变化并重启php
自己撸一个框架,需要监控代码变化 安装fswatch brew install fswatch shell重启PHP脚本reload.sh #!/bin/sh do ps -ef | grep php ...
- linux 监控文件变化
介绍 有时候我们常需要当文件变化的时候便触发某些脚本操作,比如说有文件更新了就同步文件到远程机器.在实现这个操作上,主要用到两个工具,一个是rsync,一个是inotifywait .inotifyw ...
- inotifywait命令如何监控文件变化?
转载自:https://segmentfault.com/a/1190000038351925 文件监控可以配合rsync实现文件自动同步,例如监听某个目录,当文件变化时,使用rsync命令将变化的文 ...
- Gulp-前端进阶A-3---如何不刷新监控文件变化?
npm install --save-dev gulp-connect npm install --save-dev gulp-livereload npm其他,前面已有 var gulp = req ...
- 使用apache common-io 监控文件变化--转
package common.io; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.common ...
- 利用nodejs监控文件变化并使用sftp上传到服务器
很久没写博客了,因为最近在用react+express做一个自己的工具型网站(其实就是夺宝岛抢拍器) 然后因为经常要改动,而且又要放到服务器上进行测试.总是要webpack,然后手动把文件上传上去,不 ...
- 使用apache common-io 监控文件变化
package common.io; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.common ...
随机推荐
- SpringMVC Controller 单例 多例
对于SpringMVC 的Controller单例还是多例.下面举例说明:第一次:类是多例,类里包含一个普通属性,一个静态属性 结果:普通属性:0.............静态属性:0 普通属性:0. ...
- Java判断一个字符串中有多少大写字母、小写字母和数字
Java判断一个字符串中有多少大写字母.小写字母和数字 思路: 大写字母就是A-Z之间,小写字母是a-z之间,数字就是0-9之间,于是做判断就好:用到的String知识点,遍历字符串, 长度方法len ...
- Velocity Obstacle
[Velocity Obstacle] Two circular objects A,B, at time t(0), with velocity V(A),V(B). A represent the ...
- 针对SO交期回写的工厂日历功能调整
针对所有SO回写的交期,在最终写入SAP系统时,如果交期落在周日的,则自动往后延迟一天到周一,前期已经开发的长节假日UI维护的功能不变(按照UI的开始和结束时间跳过此段时间不规划). 当加1天时落在国 ...
- StringBuffer类和String类(原文地址 : http://www.cnblogs.com/springcsc/archive/2009/12/03/1616330.html)
StringBuffer类和String一样,也用来代表字符串,只是由于StringBuffer的内部实现方式和String不同,所以StringBuffer在进行字符串处理时,不生成新的对象,在内存 ...
- Python之逻辑回归模型来预测
建立一个逻辑回归模型来预测一个学生是否被录取. import numpy as np import pandas as pd import matplotlib.pyplot as plt impor ...
- 第三章 列表(e)插入排序
- js回调函数,检测这个值是否重复
//校验提交的数据是否重复 /** * url:后端的查询地址 * filedVal: 要传到后台的值 * ele:要绑定显示的元素,一般就是当前的input就可以,直接在其后边追加显示 * fn:回 ...
- axaj 的回调
//为了动态生成表格获取数据用ajax获取servlet回调数据 <script> $.ajax({ url = "servlet地址", type : "p ...
- HDU-1069.MonkeyandBanana(LIS)
本题大意:给出n个长方体,每种长方体不限量,让你求出如何摆放长方体使得最后得到的总高最大,摆设要求为,底层的长严格大于下层的长,底层的宽严格大于下层的宽. 本题思路:一开始没有啥思路...首先应该想到 ...