javawatchservice

is Java WatchService per JVM or can an app start multiple?


FileSystems.getDefault().newWatchService();

Does that create a new watchService or just give a singleton object?

it says:

@return a new watch service

Some post I read made me think there might only be 1 and so if you do a .take() or .poll() one thread might get another threads watchKey event. I thought maybe I need to use one but now I am not so sure because I do have 2 or so running and they seemed to work but I have not explicitly tested it.

Anyone know if you can use multiple watchServices in one app?


Solution

  • Going by the source code here it seems that each time it is called it returns a new WatchService

    class WindowsFileSystem
        extends FileSystem
    {
    ..............................
    ..............................
    @Override
        public WatchService newWatchService()
            throws IOException
        {
            return new WindowsWatchService(this);
        }
    }
    

    this here refers to the WindowsFileSystem object ( I am checking this on Windows JVM ) which is static variable and hence single per JVM

    public final class FileSystems {
        private FileSystems() {
        }
    .................
    .................
    public static FileSystem getDefault() {
            return DefaultFileSystemHolder.defaultFileSystem;
        }
    
    }
    

    So we can conclude that the FileSystem object is global, however WatchService can be as many as created - all having reference to the global FileSystem.