終わらない(かもしれない)仕事を時間制限をつけて実行します。
ここはスレッドを用いたクラスを用います。
スレッドを synchronized された関数で呼び出します。
一定時間のち interrupt() を呼び出してスレッドを終了します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FileTask task=new FileTask(fn); | |
try { | |
Thread.sleep(10); | |
task.interrupt(); | |
if(task.retrieved && task.exists){ | |
// file exists | |
}else{ | |
// otherwise | |
} | |
} catch (InterruptedException e) { | |
// time out | |
} |
FileTask の定義です。
時間がかかるファイルアクセスをスレッドで実行します。コマンドを走らせて終了時フラグをセットします。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FileTask extends Thread{ | |
boolean retrieved=false; | |
boolean exists=false; | |
String fn=""; | |
FileTask(String fn){ | |
this.fn=fn; | |
start(); | |
} | |
public void run(){ | |
try{ | |
File file=new File(fn); | |
String[] list=file.list(); | |
if(list!=null) | |
{ | |
exists=true; | |
} | |
retrieved=true; | |
}catch(Exception e){ | |
log.error("File access error",e); | |
} | |
} | |
} |
これで終わらない仕事は強制終了です。