6

Java 7 で nio.2 を使用すると、次のような監視サービスを作成できます。

WatchService watcher = FileSystems.getDefault().newWatchService();

次に、バックグラウンド スレッドが開始され、無限ループ内でファイル システム イベントがポーリングされます。このスレッドの名前は「Thread-n」です。これは、スレッド ダンプを調査したり、セッションのプロファイリングを行ったりするときに少し厄介です。

そのスレッドの名前を変更できますか?

4

1 に答える 1

2

実装を見ると、それは直接可能ではないようです。少しハックしても構わない場合は、スレッドを見つけて名前を変更できます。

(//TODO: エラー チェックを配置する) のようなもの:

Set<Thread> threadsBefore = Thread.getAllStackTraces().keySet();
WatchService ws = FileSystems.getDefault().newWatchService();

//I don't need to wait here on my machine but YMMV

Set<Thread> threadsAfter = Thread.getAllStackTraces().keySet();
threadsAfter.removeAll(threadsBefore);
Thread wsThread = threadsAfter.toArray(new Thread[1])[0];

System.out.println("wsThread = " + wsThread);

wsThread.setName("WatchService Thread");

Set<Thread> justChecking = Thread.getAllStackTraces().keySet();
System.out.println("justChecking = " + justChecking);
于 2013-08-08T15:50:02.287 に答える