java守護線程讀取設定檔
對於某些應用需要即時讀取設定檔,但是讀取的頻率非常高,比如1秒100次以上,修改設定檔的頻率遠遠低於讀取頻率。此時如果當程式執行的時候每次都
讀取設定檔,那麼系統的io可能會有些壓力,因此可以做一個守護線程每隔一段時間(例如1分鐘)讀取一次設定檔,代碼直接取最新的設定檔的值來執
行,這樣既降低了讀取設定檔的頻率又獲得了較好的即時性。
代碼如下: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);
- in.close();
- 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"
));
- }
-
- }
-
- }
其中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