Skip to content

Commit

Permalink
call SelectionKey#isValid before readyOps, to prevent CancelledKeyExc…
Browse files Browse the repository at this point in the history
…eption
  • Loading branch information
HoneyryderChuck committed Nov 14, 2017
1 parent 75f19d3 commit 38e8600
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
6 changes: 6 additions & 0 deletions ext/nio4r/org/nio4r/Monitor.java
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,16 @@ public IRubyObject removeInterest(ThreadContext context, IRubyObject interest) {

@JRubyMethod
public IRubyObject readiness(ThreadContext context) {
if(!key.isValid())
return this.interests;
return Nio4r.interestOpsToSymbol(context.getRuntime(), key.readyOps());
}

@JRubyMethod(name = "readable?")
public IRubyObject isReadable(ThreadContext context) {
Ruby runtime = context.getRuntime();
if (!this.key.isValid())
return runtime.getTrue();
int readyOps = this.key.readyOps();

if((readyOps & SelectionKey.OP_READ) != 0 || (readyOps & SelectionKey.OP_ACCEPT) != 0) {
Expand All @@ -120,6 +124,8 @@ public IRubyObject isReadable(ThreadContext context) {
@JRubyMethod(name = {"writable?", "writeable?"})
public IRubyObject writable(ThreadContext context) {
Ruby runtime = context.getRuntime();
if (!this.key.isValid())
return runtime.getTrue();
int readyOps = this.key.readyOps();

if((readyOps & SelectionKey.OP_WRITE) != 0 || (readyOps & SelectionKey.OP_CONNECT) != 0) {
Expand Down
2 changes: 1 addition & 1 deletion ext/nio4r/org/nio4r/Selector.java
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ private void cancelKeys() {
// Remove connect interest from connected sockets
// See: http://stackoverflow.com/questions/204186/java-nio-select-returns-without-selected-keys-why
private void processKey(SelectionKey key) {
if((key.readyOps() & SelectionKey.OP_CONNECT) != 0) {
if(key.isValid() && (key.readyOps() & SelectionKey.OP_CONNECT) != 0) {
int interestOps = key.interestOps();

interestOps &= ~SelectionKey.OP_CONNECT;
Expand Down

0 comments on commit 38e8600

Please sign in to comment.