From 902321c4e1d2cf942d5d311a4bbd0c29a3d1e329 Mon Sep 17 00:00:00 2001 From: Lyubomir Marinov Date: Fri, 4 Mar 2016 20:09:20 -0600 Subject: [PATCH 1/6] Splits a file into multiple files (for the purposes of readability). --- .../org/ice4j/socket/jdk8/DatagramBuffer.java | 92 ++ .../ice4j/socket/jdk8/MuxServerSocket.java | 54 + .../socket/jdk8/MuxServerSocketChannel.java | 1063 +---------------- .../ice4j/socket/jdk8/MuxingServerSocket.java | 54 + .../jdk8/MuxingServerSocketChannel.java | 945 +++++++++++++++ 5 files changed, 1146 insertions(+), 1062 deletions(-) create mode 100644 src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java create mode 100644 src/main/java/org/ice4j/socket/jdk8/MuxServerSocket.java create mode 100644 src/main/java/org/ice4j/socket/jdk8/MuxingServerSocket.java create mode 100644 src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java diff --git a/src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java b/src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java new file mode 100644 index 0000000..9c6593e --- /dev/null +++ b/src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java @@ -0,0 +1,92 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2015 Atlassian Pty Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ice4j.socket.jdk8; + +import java.net.*; +import java.nio.*; + +/** + * Associates a {@link ByteBuffer} with a {@link DatagramPacket} so that the + * {@code ByteBuffer} may be used for writing into a {@code byte} array and the + * {@code DatagramPacket} may be used for reader from the same {@code byte} + * array. + * + * @author Lyubomir Marinov + */ +class DatagramBuffer +{ + /** + * The {@code ByteBuffer} which is associated with {@link #datagramPacket} + * and shares its backing {@code array} with. + */ + private final ByteBuffer byteBuffer; + + /** + * The {@code DatagramPacket} which is associated with {@link #byteBuffer} + * and shares its {@code data} with. + */ + private final DatagramPacket datagramPacket; + + /** + * The latest/last time in milliseconds at which {@code byte}s were written + * into this {@code DatagramBuffer}. + */ + long timestamp = -1; + + /** + * Initializes a new {@code DatagramBuffer} instance with a specific + * capacity of {@code byte}s shared between a {@code ByteBuffer} and a + * {@code DatagramPacket}. + * + * @param capacity the maximum number of {@code byte}s to be written into + * and read from the new instance + */ + public DatagramBuffer(int capacity) + { + byteBuffer = ByteBuffer.allocate(capacity); + datagramPacket + = new DatagramPacket( + byteBuffer.array(), + /* offset */ 0, + /* length */ 0); + } + + /** + * Gets the {@code ByteBuffer} (view) of this instance. + * + * @return the {@code ByteBuffer} (view) of this instance + */ + public ByteBuffer getByteBuffer() + { + return byteBuffer; + } + + /** + * Gets the {@code DatagramPacket} (view) of this instance. The + * {@code length} of the {@code DatagramPacket} equals the {@code position} + * of the {@code ByteBuffer} so that the {@code byte}s written into the + * {@code ByteBuffer} may be read from the {@code DatagramPacket}. + * + * @return the {@code DatagramPacket} (view) of this instance + */ + public DatagramPacket getDatagramPacket() + { + datagramPacket.setLength(byteBuffer.position()); + return datagramPacket; + } +} diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocket.java b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocket.java new file mode 100644 index 0000000..0be988b --- /dev/null +++ b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocket.java @@ -0,0 +1,54 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2015 Atlassian Pty Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ice4j.socket.jdk8; + +import java.io.*; +import java.net.*; +import org.ice4j.socket.*; + +/** + * Represents a {@link ServerSocket} associated with a + * {@code MuxServerSocketChannel}. + * + * @author Lyubomir Marinov + */ +class MuxServerSocket + extends DelegatingServerSocket +{ + /** + * Initializes a new {@code MuxServerSocket} instance which delegates (its + * method calls) to a specific {@code MuxingServerSocket} and is associated + * with a specific {@code MuxServerSocketChannel}. + * + * @param delegate the {@code MuxingServerSocket} the new instance is to + * delegate (its method calls) to. Technically, it is the {@code socket} of + * the {@code delegate} of {@code channel}. + * @param channel the {@code MuxServerSocketChannel} associated with the new + * instance + * @throws IOException if an I/O error occurs + */ + public MuxServerSocket( + MuxingServerSocket delegate, + MuxServerSocketChannel channel) + throws IOException + { + super( + MuxServerSocketChannel.assertIsNotNull(delegate, "delegate"), + MuxServerSocketChannel.assertIsNotNull(channel, "channel")); + } +} diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java index f7702aa..a256ee7 100644 --- a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java +++ b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java @@ -19,11 +19,8 @@ package org.ice4j.socket.jdk8; import java.io.*; import java.net.*; -import java.nio.*; import java.nio.channels.*; import java.util.*; - -import org.ice4j.ice.harvest.*; import org.ice4j.socket.*; /** @@ -33,47 +30,8 @@ import org.ice4j.socket.*; * @author Lyubomir Marinov */ public class MuxServerSocketChannel - extends DelegatingServerSocketChannel + extends DelegatingServerSocketChannel { - /** - * The maximum number of {@code byte}s to be read from - * {@link SocketChannel}s accepted by {@link MuxingServerSocketChannel}s in - * order to demultiplex (i.e. filter) them into - * {@code MuxServerSocketChannel}s. - */ - private static final int SOCKET_CHANNEL_READ_CAPACITY - = Math.max( - GoogleTurnSSLCandidateHarvester.SSL_CLIENT_HANDSHAKE.length, - Math.max( - HttpDemuxFilter.REQUEST_METHOD_MAX_LENGTH + 1 /* SP */, - HttpDemuxFilter.TLS_MIN_LENGTH)); - - /** - * The maximum number of milliseconds to wait for an accepted - * {@code SocketChannel} to provide incoming/readable data before it is - * considered abandoned by the client. - */ - private static final int SOCKET_CHANNEL_READ_TIMEOUT - = MuxServerSocketChannelFactory.SOCKET_CHANNEL_READ_TIMEOUT; - - /** - * Reference to 0.0.0.0 IPv4 or 0::0 IPv6 address for "wildcard" matching - * purposes. - */ - private static final InetAddress ANY_LOCAL_ADDRESS; - - static - { - try - { - ANY_LOCAL_ADDRESS = InetAddress.getByName("::"); - } - catch (UnknownHostException e) - { - throw new RuntimeException(e); - } - } - /** * Asserts that t is not null by throwing a * NullPointerException if it is. @@ -95,16 +53,6 @@ public class MuxServerSocketChannel return t; } - /** - * Closes a {@code Channel} and swallows any {@link IOException}. - * - * @param channel the {@code Channel} to close - */ - public static void closeNoExceptions(Channel channel) - { - MuxServerSocketChannelFactory.closeNoExceptions(channel); - } - /** * Opens and binds a new {@code MuxServerSocketChannel} instance. If there * are other (existing) {@code MuxServerSocketChannel} open and bound on the @@ -326,1013 +274,4 @@ public class MuxServerSocketChannel } return b; } - - /** - * Associates a {@link ByteBuffer} with a {@link DatagramPacket} so that the - * {@code ByteBuffer} may be used for writing into a {@code byte} array and - * the {@code DatagramPacket} may be used for reader from the same - * {@code byte} array. - */ - private static class DatagramBuffer - { - /** - * The {@code ByteBuffer} which is associated with - * {@link #datagramPacket} and shares its backing {@code array} with. - */ - private final ByteBuffer byteBuffer; - - /** - * The {@code DatagramPacket} which is associated with - * {@link #byteBuffer} and shares its {@code data} with. - */ - private final DatagramPacket datagramPacket; - - /** - * The latest/last time in milliseconds at which {@code byte}s were - * written into this {@code DatagramBuffer}. - */ - long timestamp = -1; - - /** - * Initializes a new {@code DatagramBuffer} instance with a specific - * capacity of {@code byte}s shared between a {@code ByteBuffer} and a - * {@code DatagramPacket}. - * - * @param capacity the maximum number of {@code byte}s to be written - * into and read from the new instance - */ - public DatagramBuffer(int capacity) - { - byteBuffer = ByteBuffer.allocate(capacity); - datagramPacket - = new DatagramPacket( - byteBuffer.array(), - /* offset */ 0, - /* length */ 0); - } - - /** - * Gets the {@code ByteBuffer} (view) of this instance. - * - * @return the {@code ByteBuffer} (view) of this instance - */ - public ByteBuffer getByteBuffer() - { - return byteBuffer; - } - - /** - * Gets the {@code DatagramPacket} (view) of this instance. The - * {@code length} of the {@code DatagramPacket} equals the - * {@code position} of the {@code ByteBuffer} so that the {@code byte}s - * written into the {@code ByteBuffer} may be read from the - * {@code DatagramPacket}. - * - * @return the {@code DatagramPacket} (view) of this instance - */ - public DatagramPacket getDatagramPacket() - { - datagramPacket.setLength(byteBuffer.position()); - return datagramPacket; - } - } - - /** - * Represents a {@link ServerSocket} associated with a - * {@code MuxingServerSocketChannel}. - */ - protected static class MuxingServerSocket - extends DelegatingServerSocket - { - /** - * Initializes a new {@code MuxingServerSocket} instance which delegates - * (its method calls) to a specific {@code ServerSocket} and is - * associated with a specific {@code MuxingServerSocketChannel}. - * - * @param delegate the {@code ServerSocket} the new instance is to - * delegate (its method calls) to. Technically, it is the {@code socket} - * of the {@code delegate} of {@code channel}. - * @param channel the {@code MuxingServerSocketChannel} associated with - * the new instance - * @throws IOException if an I/O error occurs - */ - public MuxingServerSocket( - ServerSocket delegate, - MuxingServerSocketChannel channel) - throws IOException - { - super( - assertIsNotNull(delegate, "delegate"), - assertIsNotNull(channel, "channel")); - } - } - - /** - * Shares a listening endpoint (i.e. an open and bound - * {@link ServerSocketChannel}) among multiple - * {@code MuxServerSocketChannel}s. Accepted {@link SocketChannel}s are - * demultiplexed based on {@link DatagramPacketFilter}s and dispatched for - * acceptance through matching {@code MuxServerSocketChannel}s. - */ - protected static class MuxingServerSocketChannel - extends DelegatingServerSocketChannel - { - /** - * The {@code Selector} which waits for incoming network connections on - * all {@link #muxingServerSocketChannels}. - */ - private static Selector acceptSelector; - - /** - * The {@code Thread} which waits for and accepts incoming network - * connections on all {@link #muxingServerSocketChannels}. - */ - private static Thread acceptThread; - - /** - * The (global) list of existing MixingServerSocketChannels. - */ - private static final List - muxingServerSocketChannels - = new LinkedList(); - - /** - * Adds a specific {@code MuxingServerSocketChannel} to the (global) - * list of existing {@code MuxingServerSocketChannel}s and schedules - * acceptance of incoming network connections on it. - * - * @param channel the {@code MuxingServerSocketChannel} to add to the - * (global) list of existing {@code MuxingServerSocketChannel}s and to - * schedule for acceptance of incoming network connections - * @throws IOException if an I/O error occurs - */ - private static void addMuxingServerSocketChannel( - MuxingServerSocketChannel channel) - throws IOException - { - synchronized (muxingServerSocketChannels) - { - muxingServerSocketChannels.add(channel); - muxingServerSocketChannels.notifyAll(); - - scheduleAccept(channel); - } - } - - /** - * Finds the first open {@code MuxingServerSocketChannel} in the - * (global) list of existing {@code MuxingServerSocketChannel}s which is - * bound to a specific local {@link SocketAddress}. - * - * @param localAddr the local {@code SocketAddress} on which the bound - * {@code MuxingServerSocketChannel} is to be found - * @return the first open {@code MuxingServerSocketChannel} in the - * (global) list of existing {@code MuxingServerSocketChannel}s which is - * bound to the specified {@code localAddr} or {@code null} - */ - private static MuxingServerSocketChannel findMuxingServerSocketChannel( - SocketAddress localAddr) - { - MuxingServerSocketChannel channel = null; - - synchronized (muxingServerSocketChannels) - { - Iterator i - = muxingServerSocketChannels.iterator(); - - while (i.hasNext()) - { - MuxingServerSocketChannel aChannel = i.next(); - - if (aChannel.isOpen()) - { - SocketAddress aLocalAddr; - - try - { - aLocalAddr = aChannel.getLocalAddress(); - } - catch (ClosedChannelException cce) - { - i.remove(); - aLocalAddr = null; - } - catch (IOException ioe) - { - aLocalAddr = null; - } - - boolean matches = aLocalAddr != null - && aLocalAddr.equals(localAddr); - - // if not the same address, let's see if the cached one - // is an "anyLocalAddress" and if so let's consider it - // a match - if (!matches - && aLocalAddr instanceof InetSocketAddress - && localAddr instanceof InetSocketAddress) - { - InetSocketAddress aLocalInetAddr - = (InetSocketAddress) aLocalAddr; - InetSocketAddress localInetAddr - = (InetSocketAddress) localAddr; - - matches = aLocalInetAddr.getAddress() - .equals(ANY_LOCAL_ADDRESS) - && aLocalInetAddr.getPort() - == localInetAddr.getPort(); - } - - if (matches) - { - channel = aChannel; - // The whole idea of using (1) a List for - // muxingServerSocketChannels instead of a Map and - // (2) an Iterator to loop over - // muxingServerSocketChannels is to aggressively - // clean up. Anyway, break as soon as possible in - // order to improve the execution speed and because - // there is an attempt to clean - // muxingServerSocketChannels up upon closing. - break; - } - } - else - { - i.remove(); - } - } - } - return channel; - } - - /** - * If {@link #acceptSelector} exists and is open, try to close it and do - * not throw an IOException. - */ - private static void maybeCloseAcceptSelector() - { - if (acceptSelector != null) - { - if (acceptSelector.isOpen()) - { - try - { - acceptSelector.close(); - } - catch (IOException ioe) - { - } - } - acceptSelector = null; - } - } - - /** - * Opens and binds a new {@code MuxServerSocketChannel} instance. If - * there are other (existing) {@code MuxServerSocketChannel} open and - * bound on the specified listening {@code endpoint}, the new instance - * will share it with them. - * - * @param properties a {@code Map} of the values to be assigned to - * properties of the underlying {@link ServerSocketChannel} which is to - * actually listen on the specified {@code endpoint}. If the new - * instance is not the first to open and bind the specified - * {@code endpoint}, the {@code properties} and their respective values - * may not be used. - * @param endpoint the IP and port the new instance is to bind to - * @param backlog the requested maximum number of pending incoming - * connections to be queued. If the new instance is not the first to - * open and bind the specified {@code endpoint}, the value may not be - * used. - * @param filter the {@code DatagramPacketFilter} to demultiplex (i.e. - * recognize) the content meant for the new instance - * @return a new {@code MuxServerSocketChannel} instance open and bound - * on the specified listening {@code endpoint} - * @throws IOException if an I/O error occurs - */ - public static MuxServerSocketChannel openAndBind( - Map properties, - SocketAddress endpoint, - int backlog, - DatagramPacketFilter filter) - throws IOException - { - // The restriction(s) on filter are imposed by - // MuxingServerSocketChannel and MuxServerSocketChannel. Assert that - // they are satisfied as early as possible though because it does - // not make sense to bind a ServerSocketChannel and initialize a new - // MuxingServerSocketChannel instance otherwise. - assertIsNotNull(filter, "filter"); - - MuxingServerSocketChannel muxingChannel; - - synchronized (muxingServerSocketChannels) - { - muxingChannel = findMuxingServerSocketChannel(endpoint); - if (muxingChannel == null) - { - ServerSocketChannel channel - = MuxServerSocketChannelFactory - .openAndBindServerSocketChannel( - properties, - endpoint, - backlog); - - muxingChannel = new MuxingServerSocketChannel(channel); - addMuxingServerSocketChannel(muxingChannel); - } - } - - return muxingChannel.createMuxServerSocketChannel(filter); - } - - /** - * Runs in {@link #acceptThread} and waits for and accepts incoming - * network connections on all {@link #muxingServerSocketChannels}. - */ - private static void runInAcceptThread() - { - do - { - Selector sel; - boolean select = false; - - synchronized (muxingServerSocketChannels) - { - if (!Thread.currentThread().equals(acceptThread)) - break; - - sel = MuxingServerSocketChannel.acceptSelector; - if (!sel.isOpen()) - break; - - // Accept from all muxingServerSocketChannels. - for (Iterator i - = muxingServerSocketChannels.iterator(); - i.hasNext();) - { - MuxingServerSocketChannel ch = i.next(); - - if (ch.isOpen()) - { - try - { - ch.accept(); - } - catch (IOException ioe) - { - // If ioe is a ClosedChannelException signalling - // that ch is closed, it will be handled at the - // end of the loop by removing ch from - // muxingServerSocketChannels. - } - - // Make sure all muxingServerSocketChannels are - // registered with acceptSelector. - if (ch.isOpen() && ch.keyFor(sel) == null) - { - try - { - ch.register(sel, SelectionKey.OP_ACCEPT); - } - catch (ClosedChannelException cce) - { - // The cce will be handled at the end of the - // loop by removing ch from - // muxingServerSocketChannels. - } - } - } - - if (ch.isOpen()) - select = true; - else - i.remove(); - } - // We've accepted from all muxingServerSocketChannels. - sel.selectedKeys().clear(); - - // If there are no muxingServerSocketChannels, we will wait - // until there are. - if (!select) - { - try - { - muxingServerSocketChannels.wait(); - } - catch (InterruptedException ie) - { - } - continue; - } - } - - // Wait for a new iteration of acceptance. - if (select) - { - try - { - sel.select(); - } - catch (ClosedSelectorException cse) - { - break; - } - catch (IOException ioe) - { - // Well, we're selecting from multiple - // SelectableChannels so we're not sure what the - // IOException signals here. - } - } - } - while (true); - } - - /** - * Schedules a specific {@code MuxingServerSocketChannel} for acceptance - * of incoming network connections in {@link #acceptThread}. - * - * @param channel the {@code MuxingServerSocketChannel} to schedule for - * acceptance of incoming network connections in {@code acceptThread} - * @throws IOException if an I/O error occurs - */ - private static void scheduleAccept(MuxingServerSocketChannel channel) - throws IOException - { - synchronized (muxingServerSocketChannels) - { - if (acceptThread == null) - { - // acceptSelector - maybeCloseAcceptSelector(); - try - { - acceptSelector = channel.provider().openSelector(); - } - catch (IOException ioe) - { - acceptSelector = Selector.open(); - } - - // acceptThread - acceptThread - = new Thread() - { - @Override - public void run() - { - try - { - runInAcceptThread(); - } - finally - { - synchronized (muxingServerSocketChannels) - { - if (Thread.currentThread().equals( - acceptThread)) - { - // acceptThread - acceptThread = null; - // acceptSelector - maybeCloseAcceptSelector(); - } - } - } - } - }; - acceptThread.setDaemon(true); - acceptThread.setName( - MuxingServerSocketChannel.class.getName() - + ".acceptThread"); - acceptThread.start(); - } - else - { - // Notify acceptThread that a new MuxingServerSocketChannel - // (e.g. channel) may have been added. - Selector sel = MuxingServerSocketChannel.acceptSelector; - - if (sel != null) - sel.wakeup(); - } - } - - // We might as well expedite the acceptance from - // muxingServerSocketChannel i.e. not wait for acceptThread and - // explicitly cause an accept iteration. - channel.accept(); - } - - /** - * The list of MuxServerSocketChannels created by and - * delegating to this instance. - */ - private final List muxServerSocketChannels - = new ArrayList(); - - /** - * The list of {@code SocketChannel}s which have been accepted by this - * {@code MuxingServerSocketChannel}, are being read from, and have not - * been accepted by the {@link DatagramPacketFilter} of any - * {@link MuxServerSocketChannel} yet. - */ - private final Queue readQ - = new LinkedList(); - - /** - * The {@code Selector} which waits for incoming packets on all - * {@code SocketChannel}s in {@link #readQ}. - */ - private final Selector readSelector; - - /** - * The {@code Thread} which waits for incoming packets on and reads them - * from all {@code SocketChannel}s in {@link #readQ}. - */ - private Thread readThread; - - /** - * The Object which synchronizes the access to the state of - * this MuxingServerSocketChannel such as - * {@link #muxServerSocketChannels} and {@link #readQ}. - */ - private final Object syncRoot = new Object(); - - /** - * Initializes a new {@code MuxingServerSocketChannel} instance which is - * to share the listening endpoint of a specific - * {@link ServerSocketChannel} among multiple - * {@code MuxServerSocketChannel}s. - * - * @param delegate the {@code ServerSocketChannel} for which the new - * instance is to provide listening endpoint sharing - * @throws IOException if an I/O error occurs - */ - public MuxingServerSocketChannel(ServerSocketChannel delegate) - throws IOException - { - super(assertIsNotNull(delegate, "delegate")); - - // If at least one MuxServerSocketChannel is configured as - // non-blocking, then MuxingServerSocketChannel (i.e. delegate) has - // to be configured as non-blocking as well. - configureBlocking(false); - - readSelector = provider().openSelector(); - } - - /** - * Adds a specific {@code MuxServerSocketChannel} to the list of - * {@code MuxServerSocketChannel}s created by and delegating to this - * instance. - * - * @param channel the {@code MuxServerSocketChannel} to add - */ - protected void addMuxServerSocketChannel(MuxServerSocketChannel channel) - { - synchronized (syncRoot) - { - muxServerSocketChannels.add(channel); - syncRoot.notifyAll(); - - // Wake readThread up in case a SocketChannel from readQ is - // accepted by the filter of the newly-added - // MuxServerSocketChannel. - scheduleRead(/* channel */ null); - } - } - - /** - * Initializes a new {@code MuxServerSocketChannel} instance which is to - * delegate to this instance and is to demultiplex incoming network - * connections and packets using a specific - * {@link DatagramPacketFilter}. - * - * @param filter the {@code DatagramPacketFilter} to be used by the new - * {@code MuxServerSocketChannel} instance to demultiplex incoming - * network connections and packets - * @return a new {@code MuxServerSocketChannel} instance which delegates - * to this instance and demultiplexes incoming network connections and - * packets using the specified {@code filter} - */ - protected MuxServerSocketChannel createMuxServerSocketChannel( - DatagramPacketFilter filter) - { - // A MuxServerSocketChannel with no filter does not make sense. It - // cannot be a fallback because DatagramPacketFilters (i.e. - // MuxServerSocketChannels) have no priorities. It cannot be a catch - // all because a SocketChannel (i.e. Socket) may be accepted by a - // single MuxServerSocketChannel only. - assertIsNotNull(filter, "filter"); - - MuxServerSocketChannel channel; - - synchronized (syncRoot) - { - Iterator i - = muxServerSocketChannels.iterator(); - - while (i.hasNext()) - { - MuxServerSocketChannel aChannel = i.next(); - - if (aChannel.isOpen()) - { - DatagramPacketFilter aFilter = aChannel.filter; - - // The implementations of Object#equals(Object) should - // be symmetric but they are written by humans so there - // is room for errors. - if (filter.equals(aFilter) || aFilter.equals(filter)) - { - // A SocketChannel (i.e. Socket) may be accepted by - // a single MuxServerSocketChannel only. - throw new IllegalArgumentException("filter"); - } - } - else - { - i.remove(); - } - } - - channel = new MuxServerSocketChannel(this, filter); - addMuxServerSocketChannel(channel); - } - - muxServerSocketChannelAdded(channel); - - return channel; - } - - /** - * Determines whether any of the {@code MuxServerSocketChannel}s created - * by and delegating to this instance demultiplexes (i.e. recognizes) a - * specific {@link SocketChannel} based on a specific - * {@link DatagramPacket} read from it and will make it available for - * acceptance. - * - * @param p the {@code DatagramPacket} read from {@code channel} which - * is to be analyzed by the {@code MuxServerSocketChannel}s created by - * and delegating to this instance - * @param channel the {@code SocketChannel} from which {@code p} was - * read and which is to possibly be demultiplexed into a - * {@code MuxServerSocketChannel} - * @return {@code true} if one of the {@code MuxServerSocketChannel}s - * created by and delegating to this instance demultiplexed the - * specified {@code channel}; otherwise, {@code false} - */ - private boolean filterAccept(DatagramPacket p, SocketChannel channel) - { - boolean b = false; - - for (Iterator i - = muxServerSocketChannels.iterator(); - i.hasNext();) - { - MuxServerSocketChannel muxChannel = i.next(); - - if (muxChannel.isOpen()) - { - try - { - b = muxChannel.filterAccept(p, channel); - if (b) - break; - } - catch (Throwable t) - { - // The implementation of DatagramPacketFilter is - // external to MuxingServerSocketChannel and we do not - // want the failure of one DatagramPacketFilter to kill - // the whole MuxingServerSocketChannel. - if (t instanceof InterruptedException) - Thread.currentThread().interrupt(); - else if (t instanceof ThreadDeath) - throw (ThreadDeath) t; - } - } - else - { - i.remove(); - } - } - return b; - } - - /** - * {@inheritDoc} - * - * Queues a {@link SocketChannel} accepted by this instance for reading - * so that it may later on be demultiplexed into a - * {@code MuxServerSocketChannel}. - */ - @Override - protected SocketChannel implAccept(SocketChannel accepted) - throws IOException - { - synchronized (syncRoot) - { - if (accepted != null && accepted.isOpen()) - { - accepted.configureBlocking(false); - - readQ.add(accepted); - syncRoot.notifyAll(); - - scheduleRead(accepted); - } - } - - return accepted; - } - - /** - * {@inheritDoc} - * - * Associates a {@link MuxingServerSocket} with this - * {@code MuxingServerSocketChannel}. - */ - @Override - protected MuxingServerSocket implSocket(ServerSocket socket) - throws IOException - { - return new MuxingServerSocket(socket, this); - } - - /** - * Attempts to read from a specific {@link SocketChannel} into a - * specific {@link ByteBuffer} without throwing an {@link IOException} - * if the reading from the {@code channel} fails or there is - * insufficient room in {@code buf} to write into. - * - * @param channel the {@code SocketChannel} to read from - * @param buf the {@code ByteBuffer} to write into - * @return the number of {@code byte}s read from {@code channel} and - * written into {@code buf} or {@code -1} if {@code channel} has reached - * the end of its stream - */ - protected int maybeRead(SocketChannel channel, ByteBuffer buf) - { - int read; - - if (buf.remaining() > 0) - { - try - { - read = channel.read(buf); - } - catch (IOException ioe) - { - // If ioe is a ClosedChannelException signalling that the - // specified channel is closed, it will be handled by the - // method caller (by removing channel from readQ). - read = 0; - } - } - else - { - read = 0; - } - return read; - } - - /** - * Notifies this MixingServerSocketChannel that a specific - * MuxServerSocketChannel was added to - * {@link #muxServerSocketChannels}. - * - * @param channel the added MuxServerSocketChannel - */ - protected void muxServerSocketChannelAdded( - MuxServerSocketChannel channel) - { - } - - /** - * Runs in {@link #readThread} and reads from all {@link SocketChannel}s - * in {@link #readQ} and serves them for demultiplexing to - * {@link #muxServerSocketChannels}. - */ - protected void runInReadThread() - { - do - { - Selector sel; - boolean select = false; - - synchronized (syncRoot) - { - if (!Thread.currentThread().equals(readThread)) - break; - - sel = this.readSelector; - if (!sel.isOpen()) - break; - - for (Iterator i = readQ.iterator(); - i.hasNext();) - { - SocketChannel ch = i.next(); - boolean remove = false; - - if (ch.isOpen()) - { - SelectionKey sk = ch.keyFor(sel); - - if (sk == null) - { - // Make sure that all SocketChannels in readQ - // are registered with readSelector. - try - { - sk = ch.register(sel, SelectionKey.OP_READ); - } - catch (ClosedChannelException cce) - { - // The cce will be handled at the end of the - // loop by removing ch from readQ. - } - } - if (sk != null && sk.isValid()) - { - // Try to read from ch. - DatagramBuffer db - = (DatagramBuffer) sk.attachment(); - - if (db == null) - { - db - = new DatagramBuffer( - SOCKET_CHANNEL_READ_CAPACITY); - sk.attach(db); - } - - int read = maybeRead(ch, db.getByteBuffer()); - - // Try to filter ch (into a - // MuxServerSocketChannel). - if (ch.isOpen()) - { - // Maintain a record of when the - // SocketChannel last provided readable data - // in order to weed out abandoned ones. - long now = System.currentTimeMillis(); - - if (read > 0 || db.timestamp == -1) - db.timestamp = now; - - DatagramPacket pkt = db.getDatagramPacket(); - - if (pkt.getLength() > 0 - && filterAccept(pkt, ch)) - { - sk.cancel(); - remove = true; - } - else if (read <= 0 - && now - db.timestamp - > SOCKET_CHANNEL_READ_TIMEOUT) - { - // The SocketChannel appears to have - // been abandoned by the client. - closeNoExceptions(ch); - } - } - } - } - - if (remove || !ch.isOpen()) - i.remove(); - else - select = true; - } - // We've read from all SocketChannels in readQ. - sel.selectedKeys().clear(); - - // If there are no SocketChannels in readQ, we will wait - // until there are. - if (!select) - { - try - { - syncRoot.wait(); - } - catch (InterruptedException ie) - { - } - continue; - } - } - - // Wait for a new iteration of acceptance. - if (select) - { - try - { - sel.select(); - } - catch (ClosedSelectorException cse) - { - break; - } - catch (IOException ioe) - { - // Well, we're selecting from multiple - // SelectableChannels so we're not sure what the - // IOException signals here. - } - } - } - while (true); - } - - /** - * Queues a specific {@link SocketChannel} to be read and demultiplexed - * into a {@code MuxServerSocketChannel}. - * - * @param channel the {@code SocketChannel} to queue for reading and - * demultiplexing - */ - protected void scheduleRead(SocketChannel channel) - { - synchronized (syncRoot) - { - if (readThread == null) - { - // readThread - readThread - = new Thread() - { - @Override - public void run() - { - try - { - runInReadThread(); - } - finally - { - synchronized (syncRoot) - { - if (Thread.currentThread().equals( - readThread)) - { - readThread = null; - } - } - } - } - }; - readThread.setDaemon(true); - readThread.setName( - MuxingServerSocketChannel.class.getName() - + ".readThread"); - readThread.start(); - } - else - { - // Notify readThread that a new SocketChannel (e.g. channel) - // may have been added. - Selector sel = this.readSelector; - - if (sel != null) - sel.wakeup(); - } - } - } - } - - /** - * Represents a {@link ServerSocket} associated with a - * {@code MuxServerSocketChannel}. - */ - public static class MuxServerSocket - extends DelegatingServerSocket - { - /** - * Initializes a new {@code MuxServerSocket} instance which delegates - * (its method calls) to a specific {@code MuxingServerSocket} and is - * associated with a specific {@code MuxServerSocketChannel}. - * - * @param delegate the {@code MuxingServerSocket} the new instance is to - * delegate (its method calls) to. Technically, it is the {@code socket} - * of the {@code delegate} of {@code channel}. - * @param channel the {@code MuxServerSocketChannel} associated with the - * new instance - * @throws IOException if an I/O error occurs - */ - public MuxServerSocket( - MuxingServerSocket delegate, - MuxServerSocketChannel channel) - throws IOException - { - super( - assertIsNotNull(delegate, "delegate"), - assertIsNotNull(channel, "channel")); - } - } } diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocket.java b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocket.java new file mode 100644 index 0000000..a2d9e93 --- /dev/null +++ b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocket.java @@ -0,0 +1,54 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2015 Atlassian Pty Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ice4j.socket.jdk8; + +import java.io.*; +import java.net.*; +import org.ice4j.socket.*; + +/** + * Represents a {@link ServerSocket} associated with a + * {@code MuxingServerSocketChannel}. + * + * @author Lyubomir Marinov + */ +class MuxingServerSocket + extends DelegatingServerSocket +{ + /** + * Initializes a new {@code MuxingServerSocket} instance which delegates + * (its method calls) to a specific {@code ServerSocket} and is associated + * with a specific {@code MuxingServerSocketChannel}. + * + * @param delegate the {@code ServerSocket} the new instance is to delegate + * (its method calls) to. Technically, it is the {@code socket} of the + * {@code delegate} of {@code channel}. + * @param channel the {@code MuxingServerSocketChannel} associated with the + * new instance + * @throws IOException if an I/O error occurs + */ + public MuxingServerSocket( + ServerSocket delegate, + MuxingServerSocketChannel channel) + throws IOException + { + super( + MuxServerSocketChannel.assertIsNotNull(delegate, "delegate"), + MuxServerSocketChannel.assertIsNotNull(channel, "channel")); + } +} diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java new file mode 100644 index 0000000..dca270a --- /dev/null +++ b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java @@ -0,0 +1,945 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2015 Atlassian Pty Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ice4j.socket.jdk8; + +import java.io.*; +import java.net.*; +import java.nio.*; +import java.nio.channels.*; +import java.util.*; +import org.ice4j.ice.harvest.*; +import org.ice4j.socket.*; + +/** + * Shares a listening endpoint (i.e. an open and bound + * {@link ServerSocketChannel}) among multiple {@code MuxServerSocketChannel}s. + * Accepted {@link SocketChannel}s are demultiplexed based on + * {@link DatagramPacketFilter}s and dispatched for acceptance through matching + * {@code MuxServerSocketChannel}s. + * + * @author Lyubomir Marinov + */ +class MuxingServerSocketChannel + extends DelegatingServerSocketChannel +{ + /** + * Reference to 0.0.0.0 IPv4 or 0::0 IPv6 address for "wildcard" matching + * purposes. + */ + private static final InetAddress ANY_LOCAL_ADDRESS; + + /** + * The {@code Selector} which waits for incoming network connections on all + * {@link #muxingServerSocketChannels}. + */ + private static Selector acceptSelector; + + /** + * The {@code Thread} which waits for and accepts incoming network + * connections on all {@link #muxingServerSocketChannels}. + */ + private static Thread acceptThread; + + /** + * The (global) list of existing MixingServerSocketChannels. + */ + private static final List + muxingServerSocketChannels + = new LinkedList(); + + /** + * The maximum number of milliseconds to wait for an accepted + * {@code SocketChannel} to provide incoming/readable data before it is + * considered abandoned by the client. + */ + private static final int SOCKET_CHANNEL_READ_TIMEOUT + = MuxServerSocketChannelFactory.SOCKET_CHANNEL_READ_TIMEOUT; + + /** + * The maximum number of {@code byte}s to be read from + * {@link SocketChannel}s accepted by {@link MuxingServerSocketChannel}s in + * order to demultiplex (i.e. filter) them into + * {@code MuxServerSocketChannel}s. + */ + private static final int SOCKET_CHANNEL_READ_CAPACITY + = Math.max( + GoogleTurnSSLCandidateHarvester.SSL_CLIENT_HANDSHAKE.length, + Math.max( + HttpDemuxFilter.REQUEST_METHOD_MAX_LENGTH + 1 /* SP */, + HttpDemuxFilter.TLS_MIN_LENGTH)); + + static + { + try + { + ANY_LOCAL_ADDRESS = InetAddress.getByName("::"); + } + catch (UnknownHostException e) + { + throw new RuntimeException(e); + } + } + + /** + * Adds a specific {@code MuxingServerSocketChannel} to the (global) list of + * existing {@code MuxingServerSocketChannel}s and schedules acceptance of + * incoming network connections on it. + * + * @param channel the {@code MuxingServerSocketChannel} to add to the + * (global) list of existing {@code MuxingServerSocketChannel}s and to + * schedule for acceptance of incoming network connections + * @throws IOException if an I/O error occurs + */ + private static void addMuxingServerSocketChannel( + MuxingServerSocketChannel channel) + throws IOException + { + synchronized (muxingServerSocketChannels) + { + muxingServerSocketChannels.add(channel); + muxingServerSocketChannels.notifyAll(); + + scheduleAccept(channel); + } + } + + /** + * Closes a {@code Channel} and swallows any {@link IOException}. + * + * @param channel the {@code Channel} to close + */ + public static void closeNoExceptions(Channel channel) + { + MuxServerSocketChannelFactory.closeNoExceptions(channel); + } + + /** + * Finds the first open {@code MuxingServerSocketChannel} in the (global) + * list of existing {@code MuxingServerSocketChannel}s which is bound to a + * specific local {@link SocketAddress}. + * + * @param localAddr the local {@code SocketAddress} on which the bound + * {@code MuxingServerSocketChannel} is to be found + * @return the first open {@code MuxingServerSocketChannel} in the (global) + * list of existing {@code MuxingServerSocketChannel}s which is bound to the + * specified {@code localAddr} or {@code null} + */ + private static MuxingServerSocketChannel findMuxingServerSocketChannel( + SocketAddress localAddr) + { + MuxingServerSocketChannel channel = null; + + synchronized (muxingServerSocketChannels) + { + Iterator i + = muxingServerSocketChannels.iterator(); + + while (i.hasNext()) + { + MuxingServerSocketChannel aChannel = i.next(); + + if (aChannel.isOpen()) + { + SocketAddress aLocalAddr; + + try + { + aLocalAddr = aChannel.getLocalAddress(); + } + catch (ClosedChannelException cce) + { + i.remove(); + aLocalAddr = null; + } + catch (IOException ioe) + { + aLocalAddr = null; + } + + boolean matches + = aLocalAddr != null && aLocalAddr.equals(localAddr); + + // If not the same address, let's see if the cached one is + // an "anyLocalAddress" and if so let's consider it a match. + if (!matches + && aLocalAddr instanceof InetSocketAddress + && localAddr instanceof InetSocketAddress) + { + InetSocketAddress aLocalInetAddr + = (InetSocketAddress) aLocalAddr; + InetSocketAddress localInetAddr + = (InetSocketAddress) localAddr; + + matches + = aLocalInetAddr.getAddress() + .equals(ANY_LOCAL_ADDRESS) + && aLocalInetAddr.getPort() + == localInetAddr.getPort(); + } + + if (matches) + { + channel = aChannel; + // The whole idea of using (1) a List for + // muxingServerSocketChannels instead of a Map and (2) + // an Iterator to loop over muxingServerSocketChannels + // is to aggressively clean up. Anyway, break as soon as + // possible in order to improve the execution speed and + // because there is an attempt to clean + // muxingServerSocketChannels up upon closing. + break; + } + } + else + { + i.remove(); + } + } + } + return channel; + } + + /** + * If {@link #acceptSelector} exists and is open, try to close it and do not + * throw an IOException. + */ + private static void maybeCloseAcceptSelector() + { + if (acceptSelector != null) + { + if (acceptSelector.isOpen()) + { + try + { + acceptSelector.close(); + } + catch (IOException ioe) + { + } + } + acceptSelector = null; + } + } + + /** + * Opens and binds a new {@code MuxServerSocketChannel} instance. If there + * are other (existing) {@code MuxServerSocketChannel} open and bound on the + * specified listening {@code endpoint}, the new instance will share it with + * them. + * + * @param properties a {@code Map} of the values to be assigned to + * properties of the underlying {@link ServerSocketChannel} which is to + * actually listen on the specified {@code endpoint}. If the new instance is + * not the first to open and bind the specified {@code endpoint}, the + * {@code properties} and their respective values may not be used. + * @param endpoint the IP and port the new instance is to bind to + * @param backlog the requested maximum number of pending incoming + * connections to be queued. If the new instance is not the first to open + * and bind the specified {@code endpoint}, the value may not be used. + * @param filter the {@code DatagramPacketFilter} to demultiplex (i.e. + * recognize) the content meant for the new instance + * @return a new {@code MuxServerSocketChannel} instance open and bound on + * the specified listening {@code endpoint} + * @throws IOException if an I/O error occurs + */ + public static MuxServerSocketChannel openAndBind( + Map properties, + SocketAddress endpoint, + int backlog, + DatagramPacketFilter filter) + throws IOException + { + // The restriction(s) on filter are imposed by MuxingServerSocketChannel + // and MuxServerSocketChannel. Assert that they are satisfied as early + // as possible though because it does not make sense to bind a + // ServerSocketChannel and initialize a new MuxingServerSocketChannel + // instance otherwise. + MuxServerSocketChannel.assertIsNotNull(filter, "filter"); + + MuxingServerSocketChannel muxingChannel; + + synchronized (muxingServerSocketChannels) + { + muxingChannel = findMuxingServerSocketChannel(endpoint); + if (muxingChannel == null) + { + ServerSocketChannel channel + = MuxServerSocketChannelFactory + .openAndBindServerSocketChannel( + properties, + endpoint, + backlog); + + muxingChannel = new MuxingServerSocketChannel(channel); + addMuxingServerSocketChannel(muxingChannel); + } + } + + return muxingChannel.createMuxServerSocketChannel(filter); + } + + /** + * Runs in {@link #acceptThread} and waits for and accepts incoming network + * connections on all {@link #muxingServerSocketChannels}. + */ + private static void runInAcceptThread() + { + do + { + Selector sel; + boolean select = false; + + synchronized (muxingServerSocketChannels) + { + if (!Thread.currentThread().equals(acceptThread)) + break; + + sel = MuxingServerSocketChannel.acceptSelector; + if (!sel.isOpen()) + break; + + // Accept from all muxingServerSocketChannels. + for (Iterator i + = muxingServerSocketChannels.iterator(); + i.hasNext();) + { + MuxingServerSocketChannel ch = i.next(); + + if (ch.isOpen()) + { + try + { + ch.accept(); + } + catch (IOException ioe) + { + // If ioe is a ClosedChannelException signalling + // that ch is closed, it will be handled at the end + // of the loop by removing ch from + // muxingServerSocketChannels. + } + + // Make sure all muxingServerSocketChannels are + // registered with acceptSelector. + if (ch.isOpen() && ch.keyFor(sel) == null) + { + try + { + ch.register(sel, SelectionKey.OP_ACCEPT); + } + catch (ClosedChannelException cce) + { + // The cce will be handled at the end of the + // loop by removing ch from + // muxingServerSocketChannels. + } + } + } + + if (ch.isOpen()) + select = true; + else + i.remove(); + } + // We've accepted from all muxingServerSocketChannels. + sel.selectedKeys().clear(); + + // If there are no muxingServerSocketChannels, we will wait + // until there are. + if (!select) + { + try + { + muxingServerSocketChannels.wait(); + } + catch (InterruptedException ie) + { + } + continue; + } + } + + // Wait for a new iteration of acceptance. + if (select) + { + try + { + sel.select(); + } + catch (ClosedSelectorException cse) + { + break; + } + catch (IOException ioe) + { + // Well, we're selecting from multiple SelectableChannels so + // we're not sure what the IOException signals here. + } + } + } + while (true); + } + + /** + * Schedules a specific {@code MuxingServerSocketChannel} for acceptance of + * incoming network connections in {@link #acceptThread}. + * + * @param channel the {@code MuxingServerSocketChannel} to schedule for + * acceptance of incoming network connections in {@code acceptThread} + * @throws IOException if an I/O error occurs + */ + private static void scheduleAccept(MuxingServerSocketChannel channel) + throws IOException + { + synchronized (muxingServerSocketChannels) + { + if (acceptThread == null) + { + // acceptSelector + maybeCloseAcceptSelector(); + try + { + acceptSelector = channel.provider().openSelector(); + } + catch (IOException ioe) + { + acceptSelector = Selector.open(); + } + + // acceptThread + acceptThread + = new Thread() + { + @Override + public void run() + { + try + { + runInAcceptThread(); + } + finally + { + synchronized (muxingServerSocketChannels) + { + if (Thread.currentThread().equals( + acceptThread)) + { + // acceptThread + acceptThread = null; + // acceptSelector + maybeCloseAcceptSelector(); + } + } + } + } + }; + acceptThread.setDaemon(true); + acceptThread.setName( + MuxingServerSocketChannel.class.getName() + + ".acceptThread"); + acceptThread.start(); + } + else + { + // Notify acceptThread that a new MuxingServerSocketChannel + // (e.g. channel) may have been added. + Selector sel = MuxingServerSocketChannel.acceptSelector; + + if (sel != null) + sel.wakeup(); + } + } + + // We might as well expedite the acceptance from + // muxingServerSocketChannel i.e. not wait for acceptThread and + // explicitly cause an accept iteration. + channel.accept(); + } + + /** + * The list of MuxServerSocketChannels created by and delegating to + * this instance. + */ + private final List muxServerSocketChannels + = new ArrayList(); + + /** + * The list of {@code SocketChannel}s which have been accepted by this + * {@code MuxingServerSocketChannel}, are being read from, and have not been + * accepted by the {@link DatagramPacketFilter} of any + * {@link MuxServerSocketChannel} yet. + */ + private final Queue readQ = new LinkedList(); + + /** + * The {@code Selector} which waits for incoming packets on all + * {@code SocketChannel}s in {@link #readQ}. + */ + private final Selector readSelector; + + /** + * The {@code Thread} which waits for incoming packets on and reads them + * from all {@code SocketChannel}s in {@link #readQ}. + */ + private Thread readThread; + + /** + * The Object which synchronizes the access to the state of this + * MuxingServerSocketChannel such as + * {@link #muxServerSocketChannels} and {@link #readQ}. + */ + private final Object syncRoot = new Object(); + + /** + * Initializes a new {@code MuxingServerSocketChannel} instance which is to + * share the listening endpoint of a specific {@link ServerSocketChannel} + * among multiple {@code MuxServerSocketChannel}s. + * + * @param delegate the {@code ServerSocketChannel} for which the new + * instance is to provide listening endpoint sharing + * @throws IOException if an I/O error occurs + */ + public MuxingServerSocketChannel(ServerSocketChannel delegate) + throws IOException + { + super(MuxServerSocketChannel.assertIsNotNull(delegate, "delegate")); + + // If at least one MuxServerSocketChannel is configured as non-blocking, + // then MuxingServerSocketChannel (i.e. delegate) has to be configured + // as non-blocking as well. + configureBlocking(false); + + readSelector = provider().openSelector(); + } + + /** + * Adds a specific {@code MuxServerSocketChannel} to the list of + * {@code MuxServerSocketChannel}s created by and delegating to this + * instance. + * + * @param channel the {@code MuxServerSocketChannel} to add + */ + protected void addMuxServerSocketChannel(MuxServerSocketChannel channel) + { + synchronized (syncRoot) + { + muxServerSocketChannels.add(channel); + syncRoot.notifyAll(); + + // Wake readThread up in case a SocketChannel from readQ is accepted + // by the filter of the newly-added MuxServerSocketChannel. + scheduleRead(/* channel */ null); + } + } + + /** + * Initializes a new {@code MuxServerSocketChannel} instance which is to + * delegate to this instance and is to demultiplex incoming network + * connections and packets using a specific {@link DatagramPacketFilter}. + * + * @param filter the {@code DatagramPacketFilter} to be used by the new + * {@code MuxServerSocketChannel} instance to demultiplex incoming network + * connections and packets + * @return a new {@code MuxServerSocketChannel} instance which delegates to + * this instance and demultiplexes incoming network connections and packets + * using the specified {@code filter} + */ + protected MuxServerSocketChannel createMuxServerSocketChannel( + DatagramPacketFilter filter) + { + // A MuxServerSocketChannel with no filter does not make sense. It + // cannot be a fallback because DatagramPacketFilters (i.e. + // MuxServerSocketChannels) have no priorities. It cannot be a catch all + // because a SocketChannel (i.e. Socket) may be accepted by a single + // MuxServerSocketChannel only. + MuxServerSocketChannel.assertIsNotNull(filter, "filter"); + + MuxServerSocketChannel channel; + + synchronized (syncRoot) + { + Iterator i + = muxServerSocketChannels.iterator(); + + while (i.hasNext()) + { + MuxServerSocketChannel aChannel = i.next(); + + if (aChannel.isOpen()) + { + DatagramPacketFilter aFilter = aChannel.filter; + + // The implementations of Object#equals(Object) should be + // symmetric but they are written by humans so there is room + // for errors. + if (filter.equals(aFilter) || aFilter.equals(filter)) + { + // A SocketChannel (i.e. Socket) may be accepted by a + // single MuxServerSocketChannel only. + throw new IllegalArgumentException("filter"); + } + } + else + { + i.remove(); + } + } + + channel = new MuxServerSocketChannel(this, filter); + addMuxServerSocketChannel(channel); + } + + muxServerSocketChannelAdded(channel); + + return channel; + } + + /** + * Determines whether any of the {@code MuxServerSocketChannel}s created by + * and delegating to this instance demultiplexes (i.e. recognizes) a + * specific {@link SocketChannel} based on a specific {@link DatagramPacket} + * read from it and will make it available for acceptance. + * + * @param p the {@code DatagramPacket} read from {@code channel} which is to + * be analyzed by the {@code MuxServerSocketChannel}s created by and + * delegating to this instance + * @param channel the {@code SocketChannel} from which {@code p} was read + * and which is to possibly be demultiplexed into a + * {@code MuxServerSocketChannel} + * @return {@code true} if one of the {@code MuxServerSocketChannel}s + * created by and delegating to this instance demultiplexed the specified + * {@code channel}; otherwise, {@code false} + */ + private boolean filterAccept(DatagramPacket p, SocketChannel channel) + { + boolean b = false; + + for (Iterator i + = muxServerSocketChannels.iterator(); + i.hasNext();) + { + MuxServerSocketChannel muxChannel = i.next(); + + if (muxChannel.isOpen()) + { + try + { + b = muxChannel.filterAccept(p, channel); + if (b) + break; + } + catch (Throwable t) + { + // The implementation of DatagramPacketFilter is external to + // MuxingServerSocketChannel and we do not want the failure + // of one DatagramPacketFilter to kill the whole + // MuxingServerSocketChannel. + if (t instanceof InterruptedException) + Thread.currentThread().interrupt(); + else if (t instanceof ThreadDeath) + throw (ThreadDeath) t; + } + } + else + { + i.remove(); + } + } + return b; + } + + /** + * {@inheritDoc} + * + * Queues a {@link SocketChannel} accepted by this instance for reading so + * that it may later on be demultiplexed into a + * {@code MuxServerSocketChannel}. + */ + @Override + protected SocketChannel implAccept(SocketChannel accepted) + throws IOException + { + synchronized (syncRoot) + { + if (accepted != null && accepted.isOpen()) + { + accepted.configureBlocking(false); + + readQ.add(accepted); + syncRoot.notifyAll(); + + scheduleRead(accepted); + } + } + + return accepted; + } + + /** + * {@inheritDoc} + * + * Associates a {@link MuxingServerSocket} with this + * {@code MuxingServerSocketChannel}. + */ + @Override + protected MuxingServerSocket implSocket(ServerSocket socket) + throws IOException + { + return new MuxingServerSocket(socket, this); + } + + /** + * Attempts to read from a specific {@link SocketChannel} into a specific + * {@link ByteBuffer} without throwing an {@link IOException} if the reading + * from the {@code channel} fails or there is insufficient room in + * {@code buf} to write into. + * + * @param channel the {@code SocketChannel} to read from + * @param buf the {@code ByteBuffer} to write into + * @return the number of {@code byte}s read from {@code channel} and written + * into {@code buf} or {@code -1} if {@code channel} has reached the end of + * its stream + */ + protected int maybeRead(SocketChannel channel, ByteBuffer buf) + { + int read; + + if (buf.remaining() > 0) + { + try + { + read = channel.read(buf); + } + catch (IOException ioe) + { + // If ioe is a ClosedChannelException signalling that the + // specified channel is closed, it will be handled by the method + // caller (by removing channel from readQ). + read = 0; + } + } + else + { + read = 0; + } + return read; + } + + /** + * Notifies this MixingServerSocketChannel that a specific + * MuxServerSocketChannel was added to + * {@link #muxServerSocketChannels}. + * + * @param channel the added MuxServerSocketChannel + */ + protected void muxServerSocketChannelAdded( + MuxServerSocketChannel channel) + { + } + + /** + * Runs in {@link #readThread} and reads from all {@link SocketChannel}s in + * {@link #readQ} and serves them for demultiplexing to + * {@link #muxServerSocketChannels}. + */ + protected void runInReadThread() + { + do + { + Selector sel; + boolean select = false; + + synchronized (syncRoot) + { + if (!Thread.currentThread().equals(readThread)) + break; + + sel = this.readSelector; + if (!sel.isOpen()) + break; + + for (Iterator i = readQ.iterator(); + i.hasNext();) + { + SocketChannel ch = i.next(); + boolean remove = false; + + if (ch.isOpen()) + { + SelectionKey sk = ch.keyFor(sel); + + if (sk == null) + { + // Make sure that all SocketChannels in readQ are + // registered with readSelector. + try + { + sk = ch.register(sel, SelectionKey.OP_READ); + } + catch (ClosedChannelException cce) + { + // The cce will be handled at the end of the + // loop by removing ch from readQ. + } + } + if (sk != null && sk.isValid()) + { + // Try to read from ch. + DatagramBuffer db + = (DatagramBuffer) sk.attachment(); + + if (db == null) + { + db + = new DatagramBuffer( + SOCKET_CHANNEL_READ_CAPACITY); + sk.attach(db); + } + + int read = maybeRead(ch, db.getByteBuffer()); + + // Try to filter ch (into a MuxServerSocketChannel). + if (ch.isOpen()) + { + // Maintain a record of when the SocketChannel + // last provided readable data in order to weed + // out abandoned ones. + long now = System.currentTimeMillis(); + + if (read > 0 || db.timestamp == -1) + db.timestamp = now; + + DatagramPacket pkt = db.getDatagramPacket(); + + if (pkt.getLength() > 0 + && filterAccept(pkt, ch)) + { + sk.cancel(); + remove = true; + } + else if (read <= 0 + && now - db.timestamp + > SOCKET_CHANNEL_READ_TIMEOUT) + { + // The SocketChannel appears to have been + // abandoned by the client. + closeNoExceptions(ch); + } + } + } + } + + if (remove || !ch.isOpen()) + i.remove(); + else + select = true; + } + // We've read from all SocketChannels in readQ. + sel.selectedKeys().clear(); + + // If there are no SocketChannels in readQ, we will wait until + // there are. + if (!select) + { + try + { + syncRoot.wait(); + } + catch (InterruptedException ie) + { + } + continue; + } + } + + // Wait for a new iteration of acceptance. + if (select) + { + try + { + sel.select(); + } + catch (ClosedSelectorException cse) + { + break; + } + catch (IOException ioe) + { + // Well, we're selecting from multiple SelectableChannels so + // we're not sure what the IOException signals here. + } + } + } + while (true); + } + + /** + * Queues a specific {@link SocketChannel} to be read and demultiplexed into + * a {@code MuxServerSocketChannel}. + * + * @param channel the {@code SocketChannel} to queue for reading and + * demultiplexing + */ + protected void scheduleRead(SocketChannel channel) + { + synchronized (syncRoot) + { + if (readThread == null) + { + // readThread + readThread + = new Thread() + { + @Override + public void run() + { + try + { + runInReadThread(); + } + finally + { + synchronized (syncRoot) + { + if (Thread.currentThread().equals( + readThread)) + { + readThread = null; + } + } + } + } + }; + readThread.setDaemon(true); + readThread.setName( + MuxingServerSocketChannel.class.getName() + + ".readThread"); + readThread.start(); + } + else + { + // Notify readThread that a new SocketChannel (e.g. channel) may + // have been added. + Selector sel = this.readSelector; + + if (sel != null) + sel.wakeup(); + } + } + } +} From 91c78880851f873f7086d05dd3b6c1cc7f8afd62 Mon Sep 17 00:00:00 2001 From: Lyubomir Marinov Date: Fri, 4 Mar 2016 20:27:09 -0600 Subject: [PATCH 2/6] Fixes warnings. --- .../socket/MuxServerSocketChannelFactory.java | 12 ++- .../socket/jdk8/MuxServerSocketChannel.java | 84 ++++++++++--------- .../jdk8/MuxingServerSocketChannel.java | 75 +++++++++-------- .../socket/jdk8/PreReadSocketChannel.java | 2 +- 4 files changed, 96 insertions(+), 77 deletions(-) diff --git a/src/main/java/org/ice4j/socket/MuxServerSocketChannelFactory.java b/src/main/java/org/ice4j/socket/MuxServerSocketChannelFactory.java index 44e8e82..b63e5c5 100644 --- a/src/main/java/org/ice4j/socket/MuxServerSocketChannelFactory.java +++ b/src/main/java/org/ice4j/socket/MuxServerSocketChannelFactory.java @@ -55,9 +55,10 @@ public class MuxServerSocketChannelFactory /** * The name of the {@code boolean} property of the {@code socket} property - * of the {@code ServerSocketChannel} returned by {@link #openAndBind(Map, - * SocketAddress, int, DatagramPacketFilter)} which specifies the value of - * the {@code SO_REUSEADDR} socket option. + * of the {@code ServerSocketChannel} returned by + * {@link #openAndBindMuxServerSocketChannel(Map, SocketAddress, int, + * DatagramPacketFilter)} which specifies the value of the + * {@code SO_REUSEADDR} socket option. */ public static final String SOCKET_REUSE_ADDRESS_PROPERTY_NAME = "socket.reuseAddress"; @@ -89,6 +90,7 @@ public class MuxServerSocketChannelFactory "ICE4J does not support sharing of listening endpoints" + " (probably because it is not running on JDK 8)."); } + Method method; if (clazz == null) @@ -128,6 +130,8 @@ public class MuxServerSocketChannelFactory } catch (IOException ioe) { + // The whole idea of the method is to close a specific Channel + // without caring about any possible IOException. } } @@ -245,7 +249,7 @@ public class MuxServerSocketChannelFactory if (value == null) on = false; else if (value instanceof Boolean) - on = ((Boolean) value).booleanValue(); + on = (Boolean) value; else on = Boolean.valueOf(value.toString()); diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java index a256ee7..0fac6da 100644 --- a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java +++ b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java @@ -93,8 +93,7 @@ public class MuxServerSocketChannel * The (ordered) list (i.e. queue) of SocketChannels to be returned * by {@link #accept()}. */ - private final Queue acceptQ - = new LinkedList(); + private final Queue acceptQ = new LinkedList<>(); /** * The {@code DatagramPacketFilter} which demultiplexes @@ -141,54 +140,66 @@ public class MuxServerSocketChannel throws IOException { SocketChannel accepted; + boolean interrupted = false; // Pop a SocketChannel from acceptQ. - do + try { - if (!isOpen()) + do { - throw new ClosedChannelException(); - } - else if (!isBound()) - { - throw new NotYetBoundException(); - } - else - { - synchronized (syncRoot) + if (!isOpen()) { - accepted = acceptQ.poll(); - if (accepted == null) + throw new ClosedChannelException(); + } + else if (!isBound()) + { + throw new NotYetBoundException(); + } + else + { + synchronized (syncRoot) { - if (isBlocking()) + accepted = acceptQ.poll(); + if (accepted == null) { - try + if (isBlocking()) { - syncRoot.wait(); + try + { + syncRoot.wait(); + } + catch (InterruptedException ie) + { + interrupted = true; + } } - catch (InterruptedException ie) + else { + break; } } - else + else if (accepted.isOpen()) { - break; + // Allow the MuxServerSocketChannel class and/or its + // super(s) to have a final say on the accepted + // SocketChannel such as wrapping it into a suitable + // specialization of DelegatingSocketChannel. + accepted = implAccept(accepted); + if (accepted != null) + break; } } - else if (accepted.isOpen()) - { - // Allow the MuxServerSocketChannel class and/or its - // super(s) to have a final say on the accepted - // SocketChannel such as wrapping it into a suitable - // specialization of DelegatingSocketChannel. - accepted = implAccept(accepted); - if (accepted != null) - break; - } } } + while (true); + } + finally + { + // Restore the interrupted state of the current thread if we've + // cleared it in the loop above. + if (interrupted) + Thread.currentThread().interrupt(); } - while (true); return accepted; } @@ -210,13 +221,8 @@ public class MuxServerSocketChannel */ protected boolean filterAccept(DatagramPacket p, SocketChannel channel) { - boolean b; - - if (filter.accept(p)) - b = qAccept(new PreReadSocketChannel(p, channel)); - else - b = false; - return b; + return + filter.accept(p) && qAccept(new PreReadSocketChannel(p, channel)); } /** diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java index dca270a..fbf3834 100644 --- a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java +++ b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java @@ -60,7 +60,7 @@ class MuxingServerSocketChannel */ private static final List muxingServerSocketChannels - = new LinkedList(); + = new LinkedList<>(); /** * The maximum number of milliseconds to wait for an accepted @@ -230,6 +230,8 @@ class MuxingServerSocketChannel } catch (IOException ioe) { + // I don't know what to do about any IOException during + // Selector#close() even if I log it. } } acceptSelector = null; @@ -369,27 +371,31 @@ class MuxingServerSocketChannel } catch (InterruptedException ie) { + // I don't know that we care about the interrupted state + // of the current thread because that the method + // runInAcceptThread() is pretty much the whole + // execution of the current thread that could + // potentially care about the interrupted state and it + // doesn't. } continue; } } - // Wait for a new iteration of acceptance. - if (select) + // Wait for a new iteration of acceptance. (The value of the local + // variable select is guaranteed to be true.) + try { - try - { - sel.select(); - } - catch (ClosedSelectorException cse) - { - break; - } - catch (IOException ioe) - { - // Well, we're selecting from multiple SelectableChannels so - // we're not sure what the IOException signals here. - } + sel.select(); + } + catch (ClosedSelectorException cse) + { + break; + } + catch (IOException ioe) + { + // Well, we're selecting from multiple SelectableChannels so + // we're not sure what the IOException signals here. } } while (true); @@ -476,7 +482,7 @@ class MuxingServerSocketChannel * this instance. */ private final List muxServerSocketChannels - = new ArrayList(); + = new ArrayList<>(); /** * The list of {@code SocketChannel}s which have been accepted by this @@ -484,7 +490,7 @@ class MuxingServerSocketChannel * accepted by the {@link DatagramPacketFilter} of any * {@link MuxServerSocketChannel} yet. */ - private final Queue readQ = new LinkedList(); + private final Queue readQ = new LinkedList<>(); /** * The {@code Selector} which waits for incoming packets on all @@ -862,27 +868,30 @@ class MuxingServerSocketChannel } catch (InterruptedException ie) { + // I don't know that we care about the interrupted state + // of the current thread because that the method + // runInReadThread() is pretty much the whole execution + // of the current thread that could potentially care + // about the interrupted state and it doesn't. } continue; } } - // Wait for a new iteration of acceptance. - if (select) + // Wait for a new iteration of acceptance. (The value of the local + // variable select is guaranteed to be true.) + try { - try - { - sel.select(); - } - catch (ClosedSelectorException cse) - { - break; - } - catch (IOException ioe) - { - // Well, we're selecting from multiple SelectableChannels so - // we're not sure what the IOException signals here. - } + sel.select(); + } + catch (ClosedSelectorException cse) + { + break; + } + catch (IOException ioe) + { + // Well, we're selecting from multiple SelectableChannels so + // we're not sure what the IOException signals here. } } while (true); diff --git a/src/main/java/org/ice4j/socket/jdk8/PreReadSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/PreReadSocketChannel.java index 85ade97..8dcc7dc 100644 --- a/src/main/java/org/ice4j/socket/jdk8/PreReadSocketChannel.java +++ b/src/main/java/org/ice4j/socket/jdk8/PreReadSocketChannel.java @@ -40,7 +40,7 @@ class PreReadSocketChannel /** * Initializes a new {@code PreReadSocketChannel} instance which is to - * prepend a specific {@link DatagrapPacket} to a specific + * prepend a specific {@link DatagramPacket} to a specific * {@link SocketChannel}. * * @param preRead the {@code DatagramPacket} to prepend to {@code delegate} From 20f39c00372a96d010fc6ba4755941299d2b335f Mon Sep 17 00:00:00 2001 From: Lyubomir Marinov Date: Fri, 4 Mar 2016 22:22:04 -0600 Subject: [PATCH 3/6] De-duplicates a couple of methods (which I suspect are buggy and I expect it to be easier to fix the bugs if there is no duplication). --- .../jdk8/MuxingServerSocketChannel.java | 383 ++++++++++-------- 1 file changed, 219 insertions(+), 164 deletions(-) diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java index fbf3834..d6c4f58 100644 --- a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java +++ b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java @@ -22,6 +22,7 @@ import java.net.*; import java.nio.*; import java.nio.channels.*; import java.util.*; +import java.util.function.*; import org.ice4j.ice.harvest.*; import org.ice4j.socket.*; @@ -301,31 +302,37 @@ class MuxingServerSocketChannel */ private static void runInAcceptThread() { - do - { - Selector sel; - boolean select = false; - - synchronized (muxingServerSocketChannels) - { - if (!Thread.currentThread().equals(acceptThread)) - break; - - sel = MuxingServerSocketChannel.acceptSelector; - if (!sel.isOpen()) - break; - - // Accept from all muxingServerSocketChannels. - for (Iterator i - = muxingServerSocketChannels.iterator(); - i.hasNext();) + runInSelectorThread( + /* syncRoot */ muxingServerSocketChannels, + /* threadSupplier */ new Supplier() { - MuxingServerSocketChannel ch = i.next(); - - if (ch.isOpen()) + @Override + public Thread get() + { + return MuxingServerSocketChannel.acceptThread; + } + }, + /* selectorSupplier */ new Supplier() + { + @Override + public Selector get() + { + return MuxingServerSocketChannel.acceptSelector; + } + }, + /* selectionKeyOps */ SelectionKey.OP_ACCEPT, + /* channels */ muxingServerSocketChannels, + /* predicate */ new BiPredicate() + { + @Override + public boolean test( + MuxingServerSocketChannel ch, + SelectionKey sk) { try { + // The idea is that all muxingServerSocketChannels + // are non-blocking. ch.accept(); } catch (IOException ioe) @@ -336,54 +343,145 @@ class MuxingServerSocketChannel // muxingServerSocketChannels. } - // Make sure all muxingServerSocketChannels are - // registered with acceptSelector. - if (ch.isOpen() && ch.keyFor(sel) == null) + return false; + } + }); + } + + /** + * Continually tests a {@link Predicate} on a set of + * {@link SelectableChannel}s. + * + * @param syncRoot the {@code Object} to synchronize the access to + * {@code threadSupplier}, {@code selectorSupplier}, {@code channels}, and + * {@code predicate}. It should be notified whenever the values supplied by + * {@code threadSupplier}, {@code selectorSupplier}, and {@code channels} + * change. + * @param threadSupplier the {@link Supplier} which is to supply the + * {@code Thread} in which the method is supposed to be running. If the + * returned value differs from the {@code Thread} in which the method is + * actually running (i.e. {@link Thread#currentThread()}, the method + * returns. In other words, {@code threadSupplier} is one of the ways to + * break out of the loop implemented by the method. The + * {@code threadSupplier} is called on while {@code syncRoot} is acquired. + * @param selectorSupplier the {@code Supplier} which is to supply the + * {@code Selector} on which the method is to await changes in the states of + * {@code channels} in order to begin a subsequent loop iteration. If the + * returned {@code Selector} is not open, the method returns. In other + * words, {@code selectorSupplier} is another way to break out of the loop + * implemented by the method. The {@code selectorSupplier} is called on + * while {@code syncRoot} is acquired. + * @param selectionKeyOps the {@link SelectionKey} operation-set bits which + * identify the states of {@code channels} whose changes trigger new loop + * iterations + * @param channels the (set of) {@code SelectableChannel}s on each of which + * {@code predicate} is to be continually tested. A loop iteration is + * triggered when at least one of {@code channels} has a state identified by + * {@code selectionKeyOps} changes. + * @param predicate the {@code Predicate} which is to be continually tested + * on {@code channels}. A loop iteration is triggered when at least one of + * {@code channels} has a state identified by {@code selectionKeyOps} + * changes. {@link BiPredicate#test(Object, Object)} is supplied with an + * element of {@code channels} and its (automatically) associated + * {@code SelectionKey} in the {@code Selector} returned by + * {@code selectorSupplier}. The {@code SelectionKey} is provided in case, + * for example, the implementation of {@code predicate} chooses to associate + * additional state with the {@code SelectableChannel} (through + * {@link SelectionKey#attach(Object)}) available throughout the whole loop. + * @param the element type of {@code channels} + */ + private static void runInSelectorThread( + Object syncRoot, + Supplier threadSupplier, + Supplier selectorSupplier, + int selectionKeyOps, + Iterable channels, + BiPredicate predicate) + { + do + { + Selector sel; + boolean select = false; + + synchronized (syncRoot) + { + if (!Thread.currentThread().equals(threadSupplier.get())) + break; + + sel = selectorSupplier.get(); + if (sel == null || !sel.isOpen()) + break; + + for (Iterator i = channels.iterator(); i.hasNext();) + { + T ch = i.next(); + boolean remove = false; + + if (ch.isOpen()) + { + SelectionKey sk = ch.keyFor(sel); + + if (sk == null) { + // Make sure that all (SelectableChannels in) + // channels are registered with (the Selector) sel. try { - ch.register(sel, SelectionKey.OP_ACCEPT); + sk = ch.register(sel, selectionKeyOps); } catch (ClosedChannelException cce) { // The cce will be handled at the end of the - // loop by removing ch from - // muxingServerSocketChannels. + // loop by removing ch from channels. } } + if (sk != null && sk.isValid()) + { + remove = predicate.test(ch, sk); + if (remove) + sk.cancel(); + } } - if (ch.isOpen()) - select = true; - else + if (remove || !ch.isOpen()) i.remove(); + else + select = true; } - // We've accepted from all muxingServerSocketChannels. + + // We've invoked the predicate on all (SelectableChannels in) + // channels. sel.selectedKeys().clear(); - // If there are no muxingServerSocketChannels, we will wait + // If there are no SelectableChannels in channels, we will wait // until there are. if (!select) { + // We're going to wait bellow and continue with the next + // iteration of the loop afterwards. Don't hold onto sel + // while waiting (because it's unnecessary). + sel = null; + try { - muxingServerSocketChannels.wait(); + syncRoot.wait(); } catch (InterruptedException ie) { // I don't know that we care about the interrupted state - // of the current thread because that the method - // runInAcceptThread() is pretty much the whole - // execution of the current thread that could - // potentially care about the interrupted state and it - // doesn't. + // of the current thread because the method + // runInSelectorThread() is (or at least should be) + // pretty much the whole execution of the current thread + // that could potentially care about the interrupted + // state and it doesn't (or at least shouldn't). } continue; } } - // Wait for a new iteration of acceptance. (The value of the local - // variable select is guaranteed to be true.) + // Wait for a new change in the state(s) of at least one element of + // channels. (The value of the local variable select is guaranteed + // to be true here.) try { sel.select(); @@ -753,8 +851,7 @@ class MuxingServerSocketChannel * * @param channel the added MuxServerSocketChannel */ - protected void muxServerSocketChannelAdded( - MuxServerSocketChannel channel) + protected void muxServerSocketChannelAdded(MuxServerSocketChannel channel) { } @@ -765,136 +862,34 @@ class MuxingServerSocketChannel */ protected void runInReadThread() { - do - { - Selector sel; - boolean select = false; - - synchronized (syncRoot) - { - if (!Thread.currentThread().equals(readThread)) - break; - - sel = this.readSelector; - if (!sel.isOpen()) - break; - - for (Iterator i = readQ.iterator(); - i.hasNext();) + runInSelectorThread( + /* syncRoot */ syncRoot, + /* threadSupplier */ new Supplier() { - SocketChannel ch = i.next(); - boolean remove = false; - - if (ch.isOpen()) + @Override + public Thread get() { - SelectionKey sk = ch.keyFor(sel); - - if (sk == null) - { - // Make sure that all SocketChannels in readQ are - // registered with readSelector. - try - { - sk = ch.register(sel, SelectionKey.OP_READ); - } - catch (ClosedChannelException cce) - { - // The cce will be handled at the end of the - // loop by removing ch from readQ. - } - } - if (sk != null && sk.isValid()) - { - // Try to read from ch. - DatagramBuffer db - = (DatagramBuffer) sk.attachment(); - - if (db == null) - { - db - = new DatagramBuffer( - SOCKET_CHANNEL_READ_CAPACITY); - sk.attach(db); - } - - int read = maybeRead(ch, db.getByteBuffer()); - - // Try to filter ch (into a MuxServerSocketChannel). - if (ch.isOpen()) - { - // Maintain a record of when the SocketChannel - // last provided readable data in order to weed - // out abandoned ones. - long now = System.currentTimeMillis(); - - if (read > 0 || db.timestamp == -1) - db.timestamp = now; - - DatagramPacket pkt = db.getDatagramPacket(); - - if (pkt.getLength() > 0 - && filterAccept(pkt, ch)) - { - sk.cancel(); - remove = true; - } - else if (read <= 0 - && now - db.timestamp - > SOCKET_CHANNEL_READ_TIMEOUT) - { - // The SocketChannel appears to have been - // abandoned by the client. - closeNoExceptions(ch); - } - } - } + return readThread; } - - if (remove || !ch.isOpen()) - i.remove(); - else - select = true; - } - // We've read from all SocketChannels in readQ. - sel.selectedKeys().clear(); - - // If there are no SocketChannels in readQ, we will wait until - // there are. - if (!select) + }, + /* selectorSupplier */ new Supplier() { - try + @Override + public Selector get() { - syncRoot.wait(); + return readSelector; } - catch (InterruptedException ie) + }, + /* selectionKeyOps */ SelectionKey.OP_READ, + /* channels */ readQ, + /* predicate */ new BiPredicate() + { + @Override + public boolean test(SocketChannel ch, SelectionKey sk) { - // I don't know that we care about the interrupted state - // of the current thread because that the method - // runInReadThread() is pretty much the whole execution - // of the current thread that could potentially care - // about the interrupted state and it doesn't. + return testRunInReadThreadPredicate(ch, sk); } - continue; - } - } - - // Wait for a new iteration of acceptance. (The value of the local - // variable select is guaranteed to be true.) - try - { - sel.select(); - } - catch (ClosedSelectorException cse) - { - break; - } - catch (IOException ioe) - { - // Well, we're selecting from multiple SelectableChannels so - // we're not sure what the IOException signals here. - } - } - while (true); + }); } /** @@ -951,4 +946,64 @@ class MuxingServerSocketChannel } } } + + /** + * Implements {@link BiPredicate#test(Object, Object)} of the + * {@code BiPredicate} utilized by {@link #runInReadThread()}. The method is + * defined explicitly for the purposes of reducing excessive indentation and + * bettering readability. Reads from {@code ch} and attempts to + * classify/filter it into a {@link MuxServerSocketChannel} for acceptance. + * If {@code ch} has not provided readable data within + * {@link #SOCKET_CHANNEL_READ_TIMEOUT}, it is forcibly closed. + * + * @param ch the {@code SocketChannel} to read from and to classify/filter + * into a {@code MuxServerSocketChannel} for acceptance + * @param sk the {@code SelectionKey} associated with {@code ch} in the + * {@code Selector} which awaits changes in the state(s) of {@code ch} + * @return {@code true} if {@code ch} is to no longer be tested; otherwise, + * {@code false} + */ + private boolean testRunInReadThreadPredicate( + SocketChannel ch, + SelectionKey sk) + { + // Try to read from ch. + DatagramBuffer db = (DatagramBuffer) sk.attachment(); + + if (db == null) + { + db = new DatagramBuffer(SOCKET_CHANNEL_READ_CAPACITY); + sk.attach(db); + } + + int read = maybeRead(ch, db.getByteBuffer()); + boolean remove = false; + + // Try to filter ch (into a MuxServerSocketChannel). + if (ch.isOpen()) + { + // Maintain a record of when the SocketChannel last provided + // readable data in order to weed out abandoned ones. + long now = System.currentTimeMillis(); + + if (read > 0 || db.timestamp == -1) + db.timestamp = now; + + DatagramPacket pkt = db.getDatagramPacket(); + + if (pkt.getLength() > 0 && filterAccept(pkt, ch)) + { + remove = true; + } + else if (read <= 0 + && now - db.timestamp > SOCKET_CHANNEL_READ_TIMEOUT) + { + // The SocketChannel appears to have been abandoned by the + // client. + closeNoExceptions(ch); + } + } + + return remove; + } } From be1b937ba10dd27b4f4bfdb9d3d724e510621836 Mon Sep 17 00:00:00 2001 From: Lyubomir Marinov Date: Sat, 5 Mar 2016 17:24:57 -0600 Subject: [PATCH 4/6] More aggressively weeds out abandoned sockets (in MuxServerSocketChannel scenarios). --- .../org/ice4j/socket/jdk8/DatagramBuffer.java | 31 +++----- .../socket/jdk8/MuxServerSocketChannel.java | 48 ++++++++++-- .../jdk8/MuxingServerSocketChannel.java | 78 ++++++++++++++++--- .../org/ice4j/socket/jdk8/Timestamped.java | 66 ++++++++++++++++ 4 files changed, 186 insertions(+), 37 deletions(-) create mode 100644 src/main/java/org/ice4j/socket/jdk8/Timestamped.java diff --git a/src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java b/src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java index 9c6593e..52dfa34 100644 --- a/src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java +++ b/src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java @@ -23,31 +23,20 @@ import java.nio.*; /** * Associates a {@link ByteBuffer} with a {@link DatagramPacket} so that the * {@code ByteBuffer} may be used for writing into a {@code byte} array and the - * {@code DatagramPacket} may be used for reader from the same {@code byte} + * {@code DatagramPacket} may be used for reading from the same {@code byte} * array. * * @author Lyubomir Marinov */ class DatagramBuffer + extends Timestamped { /** - * The {@code ByteBuffer} which is associated with {@link #datagramPacket} - * and shares its backing {@code array} with. - */ - private final ByteBuffer byteBuffer; - - /** - * The {@code DatagramPacket} which is associated with {@link #byteBuffer} - * and shares its {@code data} with. + * The {@code DatagramPacket} which is associated with the + * {@link ByteBuffer} {@link #o} and shares its {@code data} with. */ private final DatagramPacket datagramPacket; - /** - * The latest/last time in milliseconds at which {@code byte}s were written - * into this {@code DatagramBuffer}. - */ - long timestamp = -1; - /** * Initializes a new {@code DatagramBuffer} instance with a specific * capacity of {@code byte}s shared between a {@code ByteBuffer} and a @@ -58,12 +47,10 @@ class DatagramBuffer */ public DatagramBuffer(int capacity) { - byteBuffer = ByteBuffer.allocate(capacity); + super(ByteBuffer.allocate(capacity)); + datagramPacket - = new DatagramPacket( - byteBuffer.array(), - /* offset */ 0, - /* length */ 0); + = new DatagramPacket(o.array(), /* offset */ 0, /* length */ 0); } /** @@ -73,7 +60,7 @@ class DatagramBuffer */ public ByteBuffer getByteBuffer() { - return byteBuffer; + return o; } /** @@ -86,7 +73,7 @@ class DatagramBuffer */ public DatagramPacket getDatagramPacket() { - datagramPacket.setLength(byteBuffer.position()); + datagramPacket.setLength(getByteBuffer().position()); return datagramPacket; } } diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java index 0fac6da..d4eb577 100644 --- a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java +++ b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java @@ -93,7 +93,8 @@ public class MuxServerSocketChannel * The (ordered) list (i.e. queue) of SocketChannels to be returned * by {@link #accept()}. */ - private final Queue acceptQ = new LinkedList<>(); + private final Queue> acceptQ + = new LinkedList<>(); /** * The {@code DatagramPacketFilter} which demultiplexes @@ -139,7 +140,7 @@ public class MuxServerSocketChannel public SocketChannel accept() throws IOException { - SocketChannel accepted; + SocketChannel accepted = null; boolean interrupted = false; // Pop a SocketChannel from acceptQ. @@ -159,8 +160,9 @@ public class MuxServerSocketChannel { synchronized (syncRoot) { - accepted = acceptQ.poll(); - if (accepted == null) + Timestamped timestamped = acceptQ.poll(); + + if (timestamped == null) { if (isBlocking()) { @@ -178,7 +180,7 @@ public class MuxServerSocketChannel break; } } - else if (accepted.isOpen()) + else if ((accepted = timestamped.o).isOpen()) { // Allow the MuxServerSocketChannel class and/or its // super(s) to have a final say on the accepted @@ -203,6 +205,39 @@ public class MuxServerSocketChannel return accepted; } + /** + * Weeds out abandoned {@code SocketChannels} from {@link #acceptQ} i.e. + * which were classified/filtered into this {@code MuxServerSocketChannel} + * but were not accepted (out of it) for a long time. + * + * @param now the (system) time in milliseconds at which the method is + * invoked + */ + void closeAbandonedSocketChannels(long now) + { + synchronized (syncRoot) + { + Collection> chs = acceptQ; + + if (!chs.isEmpty()) + { + for (Iterator> i = chs.iterator(); + i.hasNext();) + { + Timestamped ch = i.next(); + + if (now - ch.timestamp + >= MuxingServerSocketChannel + .SOCKET_CHANNEL_READ_TIMEOUT) + { + i.remove(); + MuxingServerSocketChannel.closeNoExceptions(ch.o); + } + } + } + } + } + /** * Determines whether the {@link #filter} of this instance accepts a * specific {@code SocketChannel} from which a specific @@ -268,7 +303,8 @@ public class MuxServerSocketChannel synchronized (syncRoot) { - if (acceptQ.offer(channel)) + if (acceptQ.offer( + new Timestamped<>(channel, System.currentTimeMillis()))) { syncRoot.notifyAll(); b = true; diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java index d6c4f58..b800976 100644 --- a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java +++ b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java @@ -63,12 +63,21 @@ class MuxingServerSocketChannel muxingServerSocketChannels = new LinkedList<>(); + /** + * The maximum number of milliseconds to wait in a + * {@link Selector#select(long)}. The timeout should be a precaution though + * i.e. (1) it should better not be necessary and (2) it should be long + * enough to not unnecessarily hurt the performance of the application. + */ + private static final int SELECTOR_SELECT_TIMEOUT + = MuxServerSocketChannelFactory.SOCKET_CHANNEL_READ_TIMEOUT; + /** * The maximum number of milliseconds to wait for an accepted * {@code SocketChannel} to provide incoming/readable data before it is * considered abandoned by the client. */ - private static final int SOCKET_CHANNEL_READ_TIMEOUT + static final int SOCKET_CHANNEL_READ_TIMEOUT = MuxServerSocketChannelFactory.SOCKET_CHANNEL_READ_TIMEOUT; /** @@ -398,6 +407,14 @@ class MuxingServerSocketChannel Iterable channels, BiPredicate predicate) { + // The timeout to use when invoking Selector#select(long) on sel (i.e. + // the Selector supplied by selectorSupplier). It purpose is twofold: + // (1) to not wait too long in Selector#select() (hence + // SELECTOR_SELECT_TIMEOUT) and (2) to weed out abandoned channels + // (hence SOCKET_CHANNEL_READ_TIMEOUT). + final int selSelectTimeout + = Math.min(SELECTOR_SELECT_TIMEOUT, SOCKET_CHANNEL_READ_TIMEOUT); + do { Selector sel; @@ -484,7 +501,10 @@ class MuxingServerSocketChannel // to be true here.) try { - sel.select(); + // Even if no element of channels has its state(s) changed, do + // wake up after selSelectTimeout milliseconds in order to weed + // out abandoned channels. + sel.select(selSelectTimeout); } catch (ClosedSelectorException cse) { @@ -631,6 +651,26 @@ class MuxingServerSocketChannel readSelector = provider().openSelector(); } + /** + * {@inheritDoc} + */ + @Override + public SocketChannel accept() + throws IOException + { + SocketChannel ch = super.accept(); + + // Weeds out abandoned SocketChannels which were classified/filtered + // into MuxServerSocketChannel but were not accepted (out of it) for a + // long time. The accept() method of MuxingServerSocketChannel is a + // suitable place to do that because it is periodically invoked (by the + // runInAcceptThread() method) on a clock (in addition to network + // activity, of course). + closeAbandonedSocketChannels(); + + return ch; + } + /** * Adds a specific {@code MuxServerSocketChannel} to the list of * {@code MuxServerSocketChannel}s created by and delegating to this @@ -651,6 +691,27 @@ class MuxingServerSocketChannel } } + /** + * Weed out {@code SocketChannel}s which were classified/filtered into + * {@code MuxServerSocketChannel} but were not accepted (out of it) for a + * long time. + */ + private void closeAbandonedSocketChannels() + { + synchronized (syncRoot) + { + Collection chs = muxServerSocketChannels; + + if (!chs.isEmpty()) + { + long now = System.currentTimeMillis(); + + for (MuxServerSocketChannel ch : chs) + ch.closeAbandonedSocketChannels(now); + } + } + } + /** * Initializes a new {@code MuxServerSocketChannel} instance which is to * delegate to this instance and is to demultiplex incoming network @@ -677,10 +738,9 @@ class MuxingServerSocketChannel synchronized (syncRoot) { - Iterator i - = muxServerSocketChannels.iterator(); - - while (i.hasNext()) + for (Iterator i + = muxServerSocketChannels.iterator(); + i.hasNext();) { MuxServerSocketChannel aChannel = i.next(); @@ -989,14 +1049,14 @@ class MuxingServerSocketChannel if (read > 0 || db.timestamp == -1) db.timestamp = now; - DatagramPacket pkt = db.getDatagramPacket(); + DatagramPacket p = db.getDatagramPacket(); - if (pkt.getLength() > 0 && filterAccept(pkt, ch)) + if (p.getLength() > 0 && filterAccept(p, ch)) { remove = true; } else if (read <= 0 - && now - db.timestamp > SOCKET_CHANNEL_READ_TIMEOUT) + && now - db.timestamp >= SOCKET_CHANNEL_READ_TIMEOUT) { // The SocketChannel appears to have been abandoned by the // client. diff --git a/src/main/java/org/ice4j/socket/jdk8/Timestamped.java b/src/main/java/org/ice4j/socket/jdk8/Timestamped.java new file mode 100644 index 0000000..a46d2e1 --- /dev/null +++ b/src/main/java/org/ice4j/socket/jdk8/Timestamped.java @@ -0,0 +1,66 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2015 Atlassian Pty Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ice4j.socket.jdk8; + +/** + * Represents an {@code Object} with a timestamp. + * + * @param the type of the {@code Object} which has a timestamp (associated) + * @author Lyubomir Marinov + */ +class Timestamped +{ + /** + * The {@code Object} associated with {@link #timestamp}. + */ + final T o; + + /** + * The timestamp (in milliseconds) associated with {@link #o}. + */ + long timestamp; + + /** + * Initializes a new {@code Timestamped} instance with a specific + * {@code Object} and a default timestamp (value). + * + * @param o the {@code Object} to associate with a timestamp + */ + public Timestamped(T o) + { + this(o, -1); + } + + /** + * Initializes a new {@code Timestamped} instance with a specific + * {@code Object} and a specific timestamp (value). + * + * @param o the {@code Object} to associate with {@code timestamp} + * @param timestamp the timestamp (in milliseconds) to associate with + * {@code o} + */ + public Timestamped(T o, long timestamp) + { + // It makes no sense to associate a timestamp with a null. + if (o == null) + throw new NullPointerException("o"); + + this.o = o; + this.timestamp = timestamp; + } +} From 7e4f410287ac2f9315c875df5f70e443b26695f6 Mon Sep 17 00:00:00 2001 From: Lyubomir Marinov Date: Tue, 8 Mar 2016 11:17:21 -0600 Subject: [PATCH 5/6] Quickly closes client sockets which do not communicate in the format expected by the server. --- .../jdk8/MuxingServerSocketChannel.java | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java index b800976..39ae79b 100644 --- a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java +++ b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java @@ -1037,7 +1037,6 @@ class MuxingServerSocketChannel } int read = maybeRead(ch, db.getByteBuffer()); - boolean remove = false; // Try to filter ch (into a MuxServerSocketChannel). if (ch.isOpen()) @@ -1050,20 +1049,37 @@ class MuxingServerSocketChannel db.timestamp = now; DatagramPacket p = db.getDatagramPacket(); + int len = p.getLength(); - if (p.getLength() > 0 && filterAccept(p, ch)) + if (len > 0) { - remove = true; + if (filterAccept(p, ch)) + { + // A MuxServerSocketChannel has accepted ch so this + // MuxingServerSocketChannel is no longer responsible for + // ch. + return true; + } + else if (len >= SOCKET_CHANNEL_READ_CAPACITY) + { + // This MuxingServerSocketChannel has read from ch as much + // as it will ever read and no existing + // MuxServerSocketChannel has accepted ch. There is no point + // in waiting anymore. + closeNoExceptions(ch); + // Allow this MuxingServerSocketChannel to clean ch up. + return false; + } } - else if (read <= 0 - && now - db.timestamp >= SOCKET_CHANNEL_READ_TIMEOUT) + + if (read <= 0 && now - db.timestamp >= SOCKET_CHANNEL_READ_TIMEOUT) { - // The SocketChannel appears to have been abandoned by the - // client. + // It appears ch has been abandoned by the client. closeNoExceptions(ch); + return false; } } - return remove; + return false; } } From 779086c9df0eb71bd1064d8c53a125ae35d197f8 Mon Sep 17 00:00:00 2001 From: Lyubomir Marinov Date: Tue, 8 Mar 2016 14:15:49 -0600 Subject: [PATCH 6/6] More quickly deliver (control over) accepted sockets in simple cases. --- .../socket/jdk8/MuxServerSocketChannel.java | 2 +- .../jdk8/MuxingServerSocketChannel.java | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java index d4eb577..57c9c9a 100644 --- a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java +++ b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java @@ -297,7 +297,7 @@ public class MuxServerSocketChannel * @return {@code true} if {@code channel} was queued for acceptance through * this instance; otherwise, {@code false} */ - private boolean qAccept(SocketChannel channel) + boolean qAccept(SocketChannel channel) { boolean b; diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java index 39ae79b..ba9ea44 100644 --- a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java +++ b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java @@ -844,6 +844,46 @@ class MuxingServerSocketChannel { accepted.configureBlocking(false); + // If there is only one (open) MuxServerSocketChannel, it is + // inefficient to read from it in a separate thread and then + // either deliver the accepted to the MuxServerSocketChannel or + // close the accepted. The situation is pretty much like no + // functionality enabled by MuxServerSocketChannel is needed: + // whoever has invoked accept() on this ServerSocketChannel is + // going to read from the accepted and either figure out that it + // is in an expected format or close it. + MuxServerSocketChannel oneAndOnly = null; + + for (MuxServerSocketChannel ch : muxServerSocketChannels) + { + if (ch.isOpen()) + { + if (oneAndOnly == null) + { + oneAndOnly = ch; + } + else + { + oneAndOnly = null; + break; + } + } + } + if (oneAndOnly != null && oneAndOnly.qAccept(accepted)) + { + // It shouldn't matter much whether null or accepted is + // returned. It sounds reasonable to return null from the + // standpoint that accepted was classified/filtered into a + // MuxServerSocketChannel and, consequently, this + // MuxingServerSocketChannel no longer possesses it. + return null; + } + + // There are multiple (open) MuxServerSocketChannels (or none + // but then the situation is weird and it's more easily handled + // as the situation with multiple) and this instance is to read + // from accepted in orde to determine where it's to be + // classified/filtered. readQ.add(accepted); syncRoot.notifyAll();