/*
 * Copyright 2014-2021 Real Logic Limited.
 *
 * 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
 *
 * https://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.agrona.nio;

import org.agrona.LangUtil;

import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.channels.Selector;

/**
 * Implements the common functionality for a transport poller.
 */
public class TransportPoller implements AutoCloseable
{
    /**
     * Reference to the {@code selectedKeys} field in the {@link Selector} class.
     */
    protected static final Field SELECTED_KEYS_FIELD;
    /**
     * Reference to the {@code publicSelectedKeys} field in the {@link Selector} class.
     */
    protected static final Field PUBLIC_SELECTED_KEYS_FIELD;
    /**
     * Number of iterations.
     */
    protected static final int ITERATION_THRESHOLD = 5;

    private static final String SELECTOR_IMPL = "sun.nio.ch.SelectorImpl";

    static
    {
        Field selectKeysField = null;
        Field publicSelectKeysField = null;

        try
        {
            final Class<?> clazz = Class.forName(SELECTOR_IMPL, false, ClassLoader.getSystemClassLoader());

            if (clazz.isAssignableFrom(Selector.open().getClass()))
            {
                selectKeysField = clazz.getDeclaredField("selectedKeys");
                selectKeysField.setAccessible(true);

                publicSelectKeysField = clazz.getDeclaredField("publicSelectedKeys");
                publicSelectKeysField.setAccessible(true);
            }
        }
        catch (final Exception ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }
        finally
        {
            SELECTED_KEYS_FIELD = selectKeysField;
            PUBLIC_SELECTED_KEYS_FIELD = publicSelectKeysField;
        }
    }

    /**
     * KeySet used by the {@link Selector}.
     */
    protected final NioSelectedKeySet selectedKeySet = new NioSelectedKeySet();

    /**
     * Reference to the {@link Selector}.
     */
    protected final Selector selector;

    /**
     * Default constructor.
     */
    public TransportPoller()
    {
        try
        {
            selector = Selector.open(); // yes, SelectorProvider, blah, blah

            SELECTED_KEYS_FIELD.set(selector, selectedKeySet);
            PUBLIC_SELECTED_KEYS_FIELD.set(selector, selectedKeySet);
        }
        catch (final Exception ex)
        {
            throw new RuntimeException(ex);
        }
    }

    /**
     * Close NioSelector down. Returns immediately.
     */
    public void close()
    {
        selector.wakeup();
        try
        {
            selector.close();
        }
        catch (final IOException ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }
    }

    /**
     * Explicit call to {@link Selector#selectNow()} followed by clearing out the set without processing.
     */
    public void selectNowWithoutProcessing()
    {
        try
        {
            selector.selectNow();
            selectedKeySet.clear();
        }
        catch (final IOException ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }
    }
}

@@ -875,16 +875,827 @@
 eable%0A%7B%0A
+    /**%0A     * System property name for the threshold beyond which individual channel/socket polling will swap to to using%0A     * a %7B@link Selector%7D.%0A     */%0A    public static final String ITERATION_THRESHOLD_PROP_NAME = %22org.agrona.transport.iteration.threshold%22;%0A%0A    /**%0A     * Default threshold beyond which individual channel/socket polling will swap to to using a %7B@link Selector%7D.%0A     */%0A    public static final int ITERATION_THRESHOLD_DEFAULT = 5;%0A%0A    /**%0A     * Threshold beyond which individual channel/socket polling will swap to to using a %7B@link Selector%7D.%0A     *%0A     * @see #ITERATION_THRESHOLD_PROP_NAME%0A     * @see #ITERATION_THRESHOLD_DEFAULT%0A     */%0A    public static final int ITERATION_THRESHOLD = Integer.getInteger(%0A        ITERATION_THRESHOLD_PROP_NAME, ITERATION_THRESHOLD_DEFAULT);%0A%0A
     /**%0A
@@ -1768,32 +1768,32 @@
 elector%7D class.%0A
-
      */%0A    prot
@@ -1830,32 +1830,33 @@
 TED_KEYS_FIELD;%0A
+%0A
     /**%0A     * R
@@ -2007,109 +2007,8 @@
 ELD;
-%0A    /**%0A     * Number of iterations.%0A     */%0A    protected static final int ITERATION_THRESHOLD = 5;
 %0A%0A  
@@ -2989,32 +2989,73 @@
 %7B@link Selector%7D
+ which will be reused to avoid allocation
 .%0A     */%0A    pr
@@ -3129,32 +3129,32 @@
 Set();%0A%0A    /**%0A
-
      * Reference
@@ -3169,32 +3169,50 @@
 %7B@link Selector%7D
+ for the transport
 .%0A     */%0A    pr

Allow for TransportPoller.ITERATION_THRESHOLD to be configurable from a system property.