2929import static java .nio .file .StandardWatchEventKinds .OVERFLOW ;
3030
3131import java .io .IOException ;
32+ import java .io .UncheckedIOException ;
3233import java .nio .file .Path ;
3334import java .nio .file .WatchEvent ;
3435import java .nio .file .WatchKey ;
3536import java .nio .file .WatchService ;
3637import java .nio .file .Watchable ;
3738import java .nio .file .WatchEvent .Kind ;
3839import java .nio .file .WatchEvent .Modifier ;
39- import java .util .Arrays ;
4040import java .util .Map ;
4141import java .util .concurrent .ConcurrentHashMap ;
42-
43- import org . checkerframework . checker . nullness . qual . NonNull ;
42+ import java . util . function . Function ;
43+ import java . util . stream . Stream ;
4444
4545public class MacWatchable implements Watchable {
4646 private final Path path ;
@@ -67,15 +67,31 @@ public WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... mod
6767 throw new IllegalArgumentException ("A `MacWatchable` must be registered with a `MacWatchService`" );
6868 }
6969
70- // Add `OVERFLOW` to the array, as this method's documentation demands.
71- // Checker Framework: The `@NonNull` cast is only temporarily unsound.
72- events = (Kind <@ NonNull ?>[]) Arrays .copyOf (events , events .length + 1 );
73- events [events .length - 1 ] = OVERFLOW ; // All elements are now `@NonNull`
70+ // Add `OVERFLOW` to the array (demanded by this method's specification)
71+ if (Stream .of (events ).noneMatch (OVERFLOW ::equals )) {
72+ events = Stream
73+ .concat (Stream .of (events ), Stream .of (OVERFLOW ))
74+ .toArray (Kind <?>[]::new );
75+ }
76+
77+ // Wrap any `IOException` thrown by the constructor of `MacWatchKey` in
78+ // an `UncheckedIOException`. Intended to be used when invoking
79+ // `computeIfAbsent`.
80+ Function <MacWatchService , MacWatchKey > newMacWatchKey = service -> {
81+ try {
82+ return new MacWatchKey (this , service );
83+ } catch (IOException e ) {
84+ throw new UncheckedIOException (e );
85+ }
86+ };
7487
75- var service = (MacWatchService ) watcher ;
76- var newKey = new MacWatchKey (this , service );
77- var oldKey = registrations .putIfAbsent (service , newKey );
78- return (oldKey != null ? oldKey : newKey ).initialize (events , modifiers );
88+ try {
89+ return registrations
90+ .computeIfAbsent ((MacWatchService ) watcher , newMacWatchKey )
91+ .initialize (events , modifiers );
92+ } catch (UncheckedIOException e ) {
93+ throw e .getCause ();
94+ }
7995 }
8096
8197 @ Override
0 commit comments