Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Java 7 NIO.2) custom name for the watch service thread

Tags:

java

java-7

nio

Using nio.2 in Java 7, when you create a watch service like that:

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

Then, a background thread is started, polling for file system events within an infinite loop. The name of this thread is "Thread-n" which is a bit of a nuisance when investigating thread dumps or during profiling sessions.

Can we change the name of that thread?

like image 301
Antoine CHAMBILLE Avatar asked Aug 08 '13 15:08

Antoine CHAMBILLE


1 Answers

Looking at the implementation, it does not seem possible directly. If you don't mind a little hack, you can find the thread and rename it.

Something like (//TODO: put error checks in place):

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);
like image 198
assylias Avatar answered Oct 19 '22 15:10

assylias