google / google/j2objc

Selector.select() does not block after SelectionKey.cancel() or SocketChannel.close()

Open
#645 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
6k
Forks
999
Avg merge
19h 20m
Merged PRs (30d)
14

Description

This can be reproduced using the following test code:

``` java
public class TestMain {

public static void main(String[] args) throws Exception {
final Selector selector = SelectorProvider.provider().openSelector();
final SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress(InetAddress.getByName("www.google.com"), 80));
new Thread() {
@Override
public void run() {
try {
channel.register(selector, SelectionKey.OP_CONNECT);

while (true) {
System.out.println("select");
selector.select();
Iterator iterator = selector.selectedKeys().iterator();

while (iterator.hasNext()) {
SelectionKey key = iterator.next();
System.out.println("OPS: " + key.interestOps());
if (key.isConnectable()) {
System.out.println("isConnectable");

channel.finishConnect();
key.interestOps(SelectionKey.OP_READ | (~SelectionKey.OP_CONNECT & key.interestOps()));
iterator.remove();

key.cancel();
((SocketChannel) key.channel()).close();
} else if (key.isReadable()) {
System.out.println("isReadable");
iterator.remove();
} else {
System.out.println("isWritable");
iterator.remove();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();

selector.wakeup();
Thread.sleep(60000);
}
}
```

When running this piece of code in Java, it outputs

```
select
select
OPS: 8
isConnectable
select
```

and then blocks.

If it is translated to objc, it loops forever. If you comment out these two lines, it will block as in Java.

``` java
// key.cancel();
// ((SocketChannel) key.channel()).close();
```

So I guess the SelectionKey.cancel or SocketChannel.close() is not translated properly so that the SelectionKey is not removed.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.