Skip to content

Commit 76eb623

Browse files
committed
Use computeIfAbsent instead of putIfAbsent
1 parent feb2f9b commit 76eb623

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

src/main/java/engineering/swat/watch/impl/mac/MacWatchable.java

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,18 @@
2929
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
3030

3131
import java.io.IOException;
32+
import java.io.UncheckedIOException;
3233
import java.nio.file.Path;
3334
import java.nio.file.WatchEvent;
3435
import java.nio.file.WatchKey;
3536
import java.nio.file.WatchService;
3637
import java.nio.file.Watchable;
3738
import java.nio.file.WatchEvent.Kind;
3839
import java.nio.file.WatchEvent.Modifier;
39-
import java.util.Arrays;
4040
import java.util.Map;
4141
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;
4444

4545
public 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

Comments
 (0)