From aeb36f1d3b4266bc804a7b15b1e4b6ad48ef413f Mon Sep 17 00:00:00 2001 From: Sohom Majumdar Date: Sat, 15 May 2021 00:12:56 +0530 Subject: [PATCH] Add a default in select too --- .../jach/channel/selector/Selector.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/main/java/io/github/daichim/jach/channel/selector/Selector.java b/src/main/java/io/github/daichim/jach/channel/selector/Selector.java index 82af6d5..40387dd 100644 --- a/src/main/java/io/github/daichim/jach/channel/selector/Selector.java +++ b/src/main/java/io/github/daichim/jach/channel/selector/Selector.java @@ -10,6 +10,7 @@ import io.github.daichim.jach.exception.NoSuchChannelElementException; import io.github.daichim.jach.exception.TooManySelectorException; import io.github.daichim.jach.internal.AfterWriteAction; +import javafx.util.Pair; import lombok.Getter; import lombok.extern.slf4j.Slf4j; @@ -17,6 +18,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; +import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; @@ -195,6 +197,47 @@ public void select() throws IllegalStateException { } } + /** + * Checks if there are any message available in any of the channel. If so then execute the + * corresponding action for the message on that channel. Otherwise, executes the default action + * provided. + * + * @param defaultAction The default action to run if none of the channels have messages + * available. + * + * @throws IllegalStateException If there is an issue with the {@link Selector} (selector's + * internal channel is closed, or there is a null channel or + * action registered with the selector). Generally these scenarios + * should not occur. + */ + public void selectOrDefault(Action defaultAction) throws IllegalStateException { + try { + if (!this.isActive()) { + throw new IllegalStateException("Selector is closed"); + } + Optional> anyChan = + this.channelActions.values() + .stream() + .map(ca -> { + Object msg = ca.getChannel().tryRead(); + return new Pair<>(msg, ca.getAction()); + }) + .filter(msgAct -> msgAct.getKey() != null) + .findAny(); + if (anyChan.isPresent()) { + Pair msgAct = anyChan.get(); + msgAct.getValue().accept(msgAct.getKey()); + } else { + defaultAction.accept(); + } + } catch (ClosedChannelException | + NoSuchChannelElementException | + NullPointerException ex) { + + throw new IllegalStateException(ex); + } + } + /** * Runs an loop over all the channels and executes the action associated with that channel as * and when a message is received on that channel. The loop breaks when all the channels are @@ -292,6 +335,7 @@ public void untilOrDefault(Action defaultAction) throws IllegalStateException { } } + private void closeChannel(String channel) { this.channelActions.remove(channel); if (this.channelActions.isEmpty()) {