顺藤摸瓜研究应用程序如何监控文件…

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