private void monitorForChanges ( ) { if ( monitorRunning ) { return ; } final Path path ; try { path = Paths . get ( configPath ) ; } catch ( final Exception e ) { LOGGER . warn ( "Cannot monitor configuration {}, disabling monitoring; {}" , configPath , e . getMessage ( ) ) ; return ; } if ( ! path . toFile ( ) . exists ( ) ) { LOGGER . debug ( "Configuration {} does not exist, disabling monitoring" , configPath ) ; return ; } final Path directoryPath = path . getParent ( ) ; try { final WatchService watchService = FileSystems . getDefault ( ) . newWatchService ( ) ; directoryPath . register ( watchService , ENTRY_MODIFY ) ; monitorThread = new Thread ( new Runnable ( ) { @ Override public void run ( ) { try { for ( ; ; ) { final WatchKey key ; try { key = watchService . take ( ) ; } catch ( final InterruptedException e ) { LOGGER . debug ( "Interrupted the configuration monitor thread." ) ; break ; } for ( final WatchEvent < ? > event : key . pollEvents ( ) ) { final WatchEvent . Kind < ? > kind = event . kind ( ) ; if ( kind == OVERFLOW ) { continue ; } // If the configuration file triggered this event, reload it final Path changed = ( Path ) event . context ( ) ; if ( changed . equals ( path . getFileName ( ) ) ) { LOGGER . info ( "Configuration {} has been updated, reloading." , path ) ; try { loadConfiguration ( ) ; } catch ( final IOException e ) { LOGGER . error ( "Failed to reload configuration {}" , configPath , e ) ; } } // reset the key final boolean valid = key . reset ( ) ; if ( ! valid ) { LOGGER . debug ( "Monitor of {} is no longer valid" , path ) ; break ; } } } } finally { try { watchService . close ( ) ; } catch ( final IOException e ) { LOGGER . error ( "Failed to stop configuration monitor" , e ) ; } } monitorRunning = false ; } } ) ; } catch ( final IOException e ) { LOGGER . error ( "Failed to start configuration monitor" , e ) ; } monitorThread . start ( ) ; monitorRunning = true ; }
Starts up monitoring of the configuration for changes .