Effectively final
Tim Fox
timvolpe at gmail.com
Sat Jul 30 02:32:47 PDT 2011
On 30/07/2011 09:24, Steven Simpson wrote:
> Hi,
>
> On 30/07/11 08:10, Tim Fox wrote:
>> Everything is done via callbacks, which always execute on the context of
>> the callee. We also provide helpers which allow you to compose the
>> results of callbacks in nice ways e.g.
>>
>> Something like:
>>
>> int callback1Result;
>> int callback2Result;
>> Composer.when(callback1,
>> callback2).do(#{sendResponse(callback1Result+callback2Result)})
>>
>> I.e. when both callback1 and callback2 have fired create a response and
>> write it back to the client. Note, no thread blocks during this.
> I'll try rewriting that without mutable locals. To fill in the blanks,
> I'm assuming there's some domain-specific scheduling methods that take
> one or more SAM-type callbacks:
>
> class Services {
> static Completion foo(Some args, FooResponseHandler action);
> static Completion bar(Some args, BarResponseHandler action);
> }
>
> interface Completion {
> void act(Runnable action);
> }
>
> I've also made them conventionally return 'Completion' so they can be
> plugged into your helper:
>
> class Composer {
> static Completion when(Completion... parts);
> }
Yes, that's more or less what we do in node.x
>
> Finally, to translate your code:
>
> void context() {
> class Anon {
> int result1, result2;
>
> void callback1(Some args) {
> // Set result1.
> }
>
> void callback2(Some args) {
> // Set result2.
> }
>
> void complete() {
> sendResponse(result1 + result2);
> }
> }
>
> Anon anon = new Anon();
> Composer.when(Services.foo(args, anon#callback1),
> Services.bar(args, anon#callback2))
> .act(anon#complete);
> }
>
> I dare say, it's not as convenient as mutable locals, but does it meet
> your needs without being too ugly/clunky?
You can take a look how we do it, the code is in github, here's an
example. (This example actually does a lot of other stuff, but the
relevant stuff is around line 195:
https://github.com/purplefox/node.x/blob/master/src/examples/java/org/nodex/examples/composition/CompositionExample.java
Compare the above Java to the exact same example written in Ruby (node.x
is not just Java, the idea is we provide the same (similar) API in
multiple JVM languages, including JRuby, Jython, Javascript
(Nashorn/Rhino?), Groovy, etc)
https://github.com/purplefox/node.x/blob/master/src/examples/ruby/composition/composition_example.rb
(around line 138)
Your examples works, but yes it's too clunky (for me anyway).
Consider another example written in Ruby:
def foo(socket)
timed_out = false
system.set_timeout(100) { timed_out = true }
socket.on_data{ puts "Got data" if !timed_out}
end
This case would be overkill to use your technique in Java (an
AtomicBoolean would do), but then I have to explain to the user why they
have to use an AtomicBoolean when there's only one thread executing it :(
>
> Cheers,
>
> Steven
>
>
More information about the lambda-dev
mailing list