Directory change monitoring method memo (Java, Kotlin)

How to use Java's WatchService, I made a note because it fit unexpectedly when I started with a light feeling. The code is Kotlin, but is it the same in Java?

class Watcher private constructor(
        val path: Path,
        val listener: (e: WatchEvent<Path>, target: Path) -> Unit
) : AutoCloseable {

    private val executor = Executors.newSingleThreadExecutor()
    private val watchService = path.fileSystem.newWatchService()

    init {
        val watchKey = path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY)

        executor.submit {
            while (true) {
                val key = watchService.take()
                assert(watchKey == key, { "Only one key is registered, so it should always match" })

                for (e in watchKey.pollEvents()) {
                    @Suppress("UNCHECKED_CAST")  //Whenever the WatchKey event is above, it is guaranteed to be Path
                    listener(
                            e as WatchEvent<Path>,
                            path.resolve(e.context())
                    )
                }
                val valid = watchKey.reset()
                if (!valid) throw RuntimeException("Shouldn't happen normally")
            }
        }
    }

    override fun close() {
        executor.shutdownNow()
        executor.awaitTermination(1, TimeUnit.SECONDS)  //This value is appropriate
        watchService.close()
    }

    companion object {
        fun watch(
                path: Path,
                listener: (e: WatchEvent<Path>, target: Path) -> Unit
        ): Watcher {
            return Watcher(path, listener)
        }
    }

}

point

  1. Explicitly canceled by calling the cancel method
  2. Implicitly canceled because the object is no longer accessible
  3. Canceled by closing the monitoring service

So, this code doesn't usually happen ...

Improvement plan

Impressions

Difficult to use ...

Recommended Posts

Directory change monitoring method memo (Java, Kotlin)
Java learning memo (method)
[Java ~ Method ~] Study memo (5)
Java Silver Study Method Memo
Create a java method [Memo] [java11]
[Java] Processing time measurement method memo
Java method
Java memo
Java method
[Java] method
[Java] method
Memo: [Java] Check the contents of the directory
Memo for migration from java to kotlin
java anything memo
Java Silver memo
java, maven memo
Java8 method reference
Java SE 7 memo
[Java] forEach method
java anything memo 2
java8 method reference
java directory creation
[Java] Random method
[Java] split method
Java specification memo
[Java] Get KFunction from Method / Constructor in Java [Kotlin]
Java pattern memo
Call a method with a Kotlin callback block from Java
[Null safety] Kotlin Java comparison memo Correct use of Null safety
JAVA DB connection method
Java development environment memo
Change seats with java
java basic knowledge memo
Java Kuche Day memo
Mac Java Home Directory
About Java method binding
About method splitting (Java)
Studying Java 8 (see method)
[Java, Kotlin] Type Variance
Java programming (class method)
java lambda expression memo
(Memo) Java for statement
Java lambda expression [memo]
Java learning memo (interface)
[Java] Implicit inheritance memo
Java learning memo (inheritance)
java competitive programming memo
[Java] Basic method notes
[Memo] Java Linked List
[Kotlin] Get Java Constructor / Method from KFunction and call it