Very cool. Do you recall how Torsten did the continuations? Are they
exception-and-replay based or does it rewrite the bytecode into a CPS
style?
-Brian
On Oct 24, 2007, at 12:55 PM, Niklas Therning wrote:
Hi guys,
I've played around with combining commons-javaflow (continuations for
Java) and MINA. The result is that I can do session.read() and wait
for
a new message without blocking the current thread. session.read() uses
javaflow to suspend the current thread and save the call stack. Then
when a new message arrives my code will be resumed right after the
call
to session.read(). session.write() and session.close() both work
similarly.
Here's a simple example I've been working on:
public class Main {
public static void main(String[] args) {
BasicConfigurator.configure();
final NioSocketConnector connector = new NioSocketConnector();
connector.getFilterChain().addLast("pcf", new
ProtocolCodecFilter(
new TextLineCodecFactory(
Charset.forName("ISO8859-1"),
LineDelimiter.WINDOWS,
LineDelimiter.WINDOWS)));
connector.getFilterChain().addLast("log", new LoggingFilter());
connector.setHandler(new ContinuationIoHandler(new
ContinuableIoHandler() {
@Continuable
public void run(ContinuableIoSession session) {
try {
System.out.println(session.read());
session.write("USER user");
System.out.println(session.read());
session.write("PASS qwerty");
System.out.println(session.read());
session.write("STAT");
System.out.println(session.read());
session.write("QUIT");
System.out.println(session.read());
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sessionCreated(IoSession session) {
}
}));
connector.connect(new InetSocketAddress("pop.example.com",
110));
}
}
This code will log in to a POP3 server and query it for the number of
messages and then log out. The nice thing about this is that you get
the
best of two worlds: simple and readable code (blocking style) yet the
scalability of non-blocking IO.
If you find this interesting I'd be more than happy to put the code in
my sandbox for you to play with. Please be aware that I've extended
commons-javaflow slightly to be able to use Java5 instrumentation to
do
the byte-code modification. I've also added the @Continuable
annotation
which marks classes and methods which should be byte-code enhanced.
--
Niklas Therning
www.spamdrain.net