Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How is NioSelectedKeySet intended to be used? #281

Closed
HKBUSeanTYH opened this issue May 24, 2023 · 2 comments
Closed

How is NioSelectedKeySet intended to be used? #281

HKBUSeanTYH opened this issue May 24, 2023 · 2 comments
Labels

Comments

@HKBUSeanTYH
Copy link

HKBUSeanTYH commented May 24, 2023

I am looking for help on how to use NioSelectedKeySet and its intended usage. Should I copy the TransportPoller and modify? What if I want to use multiple selectors? with static Fields in the transport poller what would happen if i instantiate multiple transport pollers?

@HKBUSeanTYH
Copy link
Author

HKBUSeanTYH commented May 25, 2023

I have tried the following which is to extend the TransportPoller provided and create methods to register channels to selector and to perform select operations. Is this the correct/intended usage?

public class SelectorOptimizer extends TransportPoller {
    private final String SELECT_MODE;
    private final int SELECT_TIMEOUT;

    public SelectorOptimizer(String selectMode, int selectTimeout){
        super();
        this.SELECT_MODE = selectMode;
        this.SELECT_TIMEOUT = selectTimeout;
    }
    
    public void registerChannel(UDPChannel channel) throws ClosedChannelException {
        channel.getCHANNEL().register(this.selector, SelectionKey.OP_READ, channel);
    }
    
    public SelectionKey[] performSelection() throws IOException {
        this.selectedKeySet.clear();
        int readyKeys;
        if (SELECT_MODE.equals("BLOCK")) {
            readyKeys = this.selector.select();
        } else if (SELECT_MODE.equals("TIMEOUT")) {
            if (SELECT_TIMEOUT != 0) {
                readyKeys = this.selector.select(SELECT_TIMEOUT);
            } else {
                readyKeys = this.selector.select(5000);
            }
        } else {
            readyKeys = this.selector.selectNow();
        }

        return selectedKeySet.keys();
    }
}

@mikeb01
Copy link
Contributor

mikeb01 commented May 14, 2024

NioSelectedKeySet is only intended to be using with TransportPoller as a workaround to avoid the memory allocation that occurs in Selector#selectedKeys. If you are running JDK 11 or later, then you should use Selector#select(Consumer<SelectionKey> action) instead of NioSelectedKeySet.

@mikeb01 mikeb01 closed this as completed May 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants