之前写过服务,需要动态加载配置文件。做法是后台启动一个线程,每隔一段时间看下文件是否发生了变化(通过大小+最后修改时间),如果有变化就重新加载。可用是可用,但感觉效率不高也不够及时。最近听闻Java NIO可以监控文件。
Java 7 NIO.2 文件监视服务简介 。 看一下类图:
具体实现有:Windows的版本,Linux的版本,轮询的版本。这就很有趣了,说明Windows和Linux应该分别有对应的API。顺藤摸瓜进行研究,看看源码吗:
Windows的源码:
WindowsWatchService.java 可以看出Windows是用IOCP来监控文件变化。
Linux的源码:
LinuxWatchService.java ,看看注释:
Linux implementation of WatchService based on inotify. In summary a background thread polls inotify plus a socket used for the wakeup mechanism. Requests to add or remove a watch, or close the watch service, cause the thread to wakeup and process the request. Events are processed by the thread which causes it to signal/queue the corresponding watch keys。
inotify这个api之前没用过,搜索下用法:
inotify -- Linux 2.6 内核中的文件系统变化通知机制 。
现在我知道如何高效地监控文件变化了。不过话说回来,一般也就监控很少数的配置文件,感觉开个线程定期看一下也够用了。但是长姿势总是好的。