Skip to content

Instantly share code, notes, and snippets.

@iconara
Created January 7, 2015 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iconara/4e41edb000a1305a9c28 to your computer and use it in GitHub Desktop.
Save iconara/4e41edb000a1305a9c28 to your computer and use it in GitHub Desktop.
JRuby issue 2420
require 'socket'
require 'thread'
port = 2**15 + rand(2**15)
lock = Mutex.new
connections = []
server_socket = TCPServer.new(port)
# this thread is the server, it accepts connections and adds
# them to the connections array
Thread.start do
loop do
# wait for new connections, since the real code also did more things
# all client connections are monitored for readability too
# this is what causes the problem, if nil is given instead of connections
# then no exception is raised from this script
acceptables, _ = IO.select([server_socket], connections, nil, 0)
if acceptables
acceptables.each do |socket|
connection, _ = socket.accept_nonblock
lock.synchronize do
connections << connection
end
end
end
end
end
# make ten connections to the server
Array.new(10) { TCPSocket.new('localhost', port) }
# wait util the server has accepted all ten connections
until lock.synchronize { connections.size == 10 }
sleep 0.01
end
# write a message to all connected clients
lock.synchronize do
connections.each do |socket|
if IO.select(nil, [socket], nil, 0)
begin
# this raises java.nio.channels.IllegalBlockingModeException in JRuby 9K
# when the socket is also monitored for writability in the server thread
# this does not raise an error in JRuby 1.7 nor MRI
socket.write_nonblock('hello world')
rescue => e
$stderr.puts('#write_nonblock failed with "%s" (%s)' % [e.message, e.class.name])
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment