Is the while loop of NIO suppose to be inside a Thread?:

?

-

Is the while of NIO suppose to be inside a Thread?

public SomeClass() {

...

thread = new Thread(new Runnable() {
while (selector.select() > 0) {
...

if (key.isWritable()) {
socketChannel.write(byteBuffer);
}

...
}
}
thread.start();
}

public void sendData(String string) {
byteBuffer = ByteBuffer.wrap(string.getBytes());
}


If I don't use a thread, calling sendData(..) is to no avail. Am I
missing something?
 
E

Esmond Pitt

- said:
Is the while of NIO suppose to be inside a Thread?

public SomeClass() {

...

thread = new Thread(new Runnable() {
while (selector.select() > 0) {
...

if (key.isWritable()) {
socketChannel.write(byteBuffer);
}

...
}
}
thread.start();
}

public void sendData(String string) {
byteBuffer = ByteBuffer.wrap(string.getBytes());
}


If I don't use a thread, calling sendData(..) is to no avail. Am I
missing something?

As socket channels are almost always writable there isn't much point in
any of this. Do the wrap, try the write: if it doesn't complete,
register for OP_WRITE and wait for it to fire; when it does, continue
the write, if it completes now deregister OP_WRITE otherwise repeat the
select(). The select() part will only really happen if you overrun the
sender. Whether you do that in the same thread or another thread is up
to you.

EJP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,438
Messages
2,571,699
Members
48,796
Latest member
Greg L.
Top