对于某些应用需要实时读取配置文件,但是读取的频率非常高,比如1秒100次以上,修改配置文件的频率远远低于读取频率。此时如果当程序执行的时候每次都 读取配置文件,那么系统的io可能会有些压力,因此可以做一个守护线程每隔一段时间(例如1分钟)读取一次配置文件,代码直接取最新的配置文件的值来执 行,这样既降低了读取配置文件的频率又获得了较好的实时性。
代码如下:
其中c.setDaemon(true)设置线程为守护线程,关于守护线程可以参考
http://www.google.cn/search?complete=1&hl=zh-CN&q=java+%E5%AE%88%E6%8A%A4%E7%BA%BF%E7%A8%8B&meta=&aq=t&oq=java+%E5%AE%88%E6%8A%A4
代码如下:
java 代码
- import java.io.InputStream;
- import java.util.Properties;
- /**
- * 系统配置文件类
- * @author sunbin
- *
- */
- public class Configation extends Thread {
- //静态属性类
- private static Properties p;
- /**
- * 默认构造方法
- */
- public Configation(){
- //
- }
- /**
- * 继承Thread必须要实现的方法
- */
- public void run(){
- while(true){
- //获取classpath中配置文件
- InputStream in = Configation.class.getClassLoader().getResourceAsStream("config.properties");
- if (p == null){
- p = new Properties();
- }
- try{
- p.load(in);
- Thread.sleep(10000);//休眠10秒后重新读取配置文件
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- /**
- * 获取配置文件的实例
- * @return
- */
- public Properties getProperties(){
- return p;
- }
- /**
- * 测试主程序
- * @param args
- */
- public static void main(String[] args){
- Configation c = new Configation();
- c.setDaemon(true);//设置线程为守护线程
- c.start();//启动线程
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- //重复打印配置文件的值,当修改配置文件后1秒立即生效
- while(true){
- Properties p = c.getProperties();
- System.out.println(p.getProperty("com.test.a"));
- }
- }
- }