29
29
import static java .nio .file .StandardWatchEventKinds .OVERFLOW ;
30
30
31
31
import java .io .IOException ;
32
+ import java .io .UncheckedIOException ;
32
33
import java .nio .file .Path ;
33
34
import java .nio .file .WatchEvent ;
34
35
import java .nio .file .WatchKey ;
35
36
import java .nio .file .WatchService ;
36
37
import java .nio .file .Watchable ;
37
38
import java .nio .file .WatchEvent .Kind ;
38
39
import java .nio .file .WatchEvent .Modifier ;
39
- import java .util .Arrays ;
40
40
import java .util .Map ;
41
41
import 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 ;
44
44
45
45
public class MacWatchable implements Watchable {
46
46
private final Path path ;
@@ -67,15 +67,31 @@ public WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... mod
67
67
throw new IllegalArgumentException ("A `MacWatchable` must be registered with a `MacWatchService`" );
68
68
}
69
69
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
+ };
74
87
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
+ }
79
95
}
80
96
81
97
@ Override
0 commit comments