Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

multithreading - Java thread blocks while registering channel with selector while select() is called. What to do?

I have a basic question. Why and how SelectableChannel's register method can be in blocking call. Let me provide a scenario.

I have created a Selector object in class Register as follows.

private static Selector selector = Selector.open();

I also have a method in same class(Register) to register the channel with the selector.

public static SelectionKey registerChannel(SelectableChannel channel, int ops)
                             throws IOException {
   channel.configureBlocking(false);
   return channel.register(selector, ops);
}

And there is another class named Request, which has method which reads the data from channels, processes and calls following method to register the channel.

selectonKey = Register.register(socketChannel, SelectionKey.OP_READ);

Here at this point the thread is blocked, not giving clue of what it is waiting for. I have verified that the selector is open. Please provide me some help to understand how can I resolve this. Is there any lock that I can release.

Any input would be appreciated.

Adding to what I described. Further tests revealed that if the Register.register method is called from the same thread, it is able to register but after that if some other thread tries to invoke the method, thread doesn,t move ahead.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a basic feature of most NIO implementations that isn't obvious from the documentation.

You need to make all register calls from the same thread that is doing your selecting or deadlocks will occur. Usually this is done by providing a queue of registrations/deregistrations/interest-changes that is written to and then selector.wakeup() is called. When the selecting thread wakes up it checks the queue and performs any requested operations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...