001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2016-2018 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.io;
020
021import java.io.IOException;
022import java.io.InterruptedIOException;
023import java.nio.channels.SelectableChannel;
024import java.nio.channels.SelectionKey;
025import java.nio.channels.Selector;
026import java.util.Set;
027import org.jgrapes.core.Component;
028import org.jgrapes.core.Components;
029import org.jgrapes.core.annotation.Handler;
030import org.jgrapes.core.events.Start;
031import org.jgrapes.core.events.Stop;
032import org.jgrapes.io.events.NioRegistration;
033
034/**
035 * A helper component that provides the central hub for non blocking
036 * I/O components. Exactly one {@code NioDispatcher} must exist in
037 * any tree with {@link NioHandler} components. 
038 */
039@SuppressWarnings("PMD.AvoidSynchronizedStatement")
040public class NioDispatcher extends Component implements Runnable {
041
042    private final Selector selector;
043    private Thread runner;
044    private final Object selectorGate = new Object();
045
046    /**
047     * Creates a new Dispatcher.
048     * 
049     * @throws IOException if an I/O exception occurred
050     */
051    public NioDispatcher() throws IOException {
052        selector = Selector.open();
053    }
054
055    /**
056     * Starts this dispatcher. A dispatcher has an associated thread that
057     * keeps it running.
058     * 
059     * @param event the event
060     */
061    @Handler
062    public void onStart(Start event) {
063        synchronized (this) {
064            if (runner != null && !runner.isInterrupted()) {
065                return;
066            }
067            runner = (Components.useVirtualThreads() ? Thread.ofVirtual()
068                : Thread.ofPlatform()).name(Components.simpleObjectName(this))
069                    .start(this);
070        }
071    }
072
073    /**
074     * Stops the thread that is associated with this dispatcher.
075     * 
076     * @param event the event
077     * @throws InterruptedException if the execution is interrupted
078     */
079    @Handler(priority = -10_000)
080    public void onStop(Stop event) throws InterruptedException {
081        synchronized (this) {
082            if (runner == null) {
083                return;
084            }
085            // It just might happen that the wakeup() occurs between the
086            // check for running and the select() in the thread's run loop,
087            // but we -- obviously -- cannot put the select() in a
088            // synchronized(this).
089            while (runner.isAlive()) {
090                runner.interrupt(); // *Should* be sufficient, but...
091                selector.wakeup(); // Make sure
092                runner.join(10);
093            }
094            runner = null;
095        }
096    }
097
098    /**
099     * Invoked once by the thread associated with the dispatcher. Handles
100     * all events from the underlying {@link Selector}.  
101     */
102    @Override
103    @SuppressWarnings({ "PMD.EmptyCatchBlock", "PMD.EmptyControlStatement",
104        "PMD.AvoidCatchingGenericException" })
105    public void run() {
106        try {
107            registerAsGenerator();
108            while (!Thread.currentThread().isInterrupted()) {
109                try {
110                    selector.select();
111                    Set<SelectionKey> selected = selector.selectedKeys();
112                    for (SelectionKey key : selected) {
113                        ((NioHandler) key.attachment())
114                            .handleOps(key.readyOps());
115                    }
116                    selected.clear();
117                    synchronized (selectorGate) {
118                        // Delay next iteration if another thread has the lock.
119                        // "Find bugs" complains, but this is really okay.
120                    }
121                } catch (InterruptedIOException | InterruptedException
122                        | Error e) {
123                    break;
124                } catch (Throwable e) {
125                    // Ignore anything else, this loop is crucial.
126                }
127            }
128        } finally {
129            unregisterAsGenerator();
130        }
131    }
132
133    /**
134     * Handle the NIO registration.
135     *
136     * @param event the event
137     * @throws IOException Signals that an I/O exception has occurred.
138     */
139    @Handler
140    public void onNioRegistration(NioRegistration event)
141            throws IOException {
142        @SuppressWarnings("PMD.CloseResource")
143        SelectableChannel channel = event.ioChannel();
144        channel.configureBlocking(false);
145        SelectionKey key;
146        synchronized (selectorGate) {
147            selector.wakeup(); // make sure selector isn't blocking
148            key = channel.register(
149                selector, event.ops(), event.handler());
150        }
151        event.setResult(new Registration(key));
152    }
153
154    /**
155     * Represents a NIO registration.
156     */
157    public class Registration extends NioRegistration.Registration {
158
159        private final SelectionKey key;
160
161        /**
162         * Instantiates a new registration.
163         *
164         * @param key the key
165         */
166        public Registration(SelectionKey key) {
167            super();
168            this.key = key;
169        }
170
171        @Override
172        public void updateInterested(int ops) {
173            synchronized (selectorGate) {
174                selector.wakeup(); // make sure selector isn't blocking
175                key.interestOps(ops);
176            }
177        }
178    }
179
180}