(Java 7 NIO.2) user name for clock service flow

Using nio.2 in Java 7 when you create a view service, for example:

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

Then the background thread starts, polling for file system events in an endless loop. The name of this thread is β€œThread-n,” which is a bit unpleasant when examining thread dumps or during profiling sessions.

Can we change the name of this stream?

+4
source share
1 answer

Looking at the implementation, it seems impossible directly. If you are not against a small hack, you can find the stream and rename it.

Something like (// TODO: puts the error check 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); 
+1
source

Source: https://habr.com/ru/post/1495985/


All Articles