tags:

views:

206

answers:

2

How would I define a new type of java.nio.channels.SelectableChannel (say for serial ports)?

A: 

You probably want to extend java.nio.channels.spi.AbstractSelectableChannel to create the implementation that you need. If you are asking for something different, you need to give a more detailed question. The JDK source code is downloadable under a few different licenses, depending on what version you are downloading. You have the option of viewing the JDK implementations (java.nio.channels.Channel, java.nio.channels.SocketChannel, etc...) to fully understand what you need to implement. If you do this, however, be careful not to copy code from the JDK source unless you can obey the license of the source code that you downloaded.

The book Java NIO may help you.

Eddie
How can you implement AbstractSelectableChannel when you don't have a SelectorProvider handy? SelectableChannel.provider() is supposed to return the provider that created the channel but the default provider can't have created your implementation.
Gili
I guess my point is that somewhere under the hood, someone must be invoking a low-level select() against file handles. It's not clear how SelectableChannel provides Selector with the information necessary to do its job. How can the latter know when my SelectableChannel is ready to read, write, etc?
Gili
+1  A: 

My understanding is that the java implementation is based on the unix select() c function (I seem to remember that the Windows implementation was slightly different)

Depending on OS (and JVM args!) different native OS functions are called, but what they have in common is that it's native code - the basic functionality is not implemented in Java.

If you want to make a lib that access the select() (or similar) of the underlying OS (which does indeed rely on filehandles), I think you are pretty much forced to use JNI. I don't believe there are any ways around it.

The Selector/SelectableChannel in Java is really an anemic subset of what select() can do.

Nuoji
In other words, there is no way to define your own SelectableChannel?
Gili
Judging from the source code to Selector and SelectableChannel I can't see any way around the fact that if you want to define your own SelectableChannel, then what you need to do is write (and register) a new SelectorProvider that provides your own new fresh implementations of Selector and SelectableChannel (they need to be paired) that support the extended functionality you want (using JNI or some other method).
Nuoji