I’ve got some JRuby code where I make extensive use of a method like:
with_robot_lock { ... do some stuff ... }
To my eye, it’s both expressive and compact. I like it. I expect you
can
easily imagine what it does, and how it’s implemented.
Now, my problem. I’ve got teammates who want to program in Java along
with
me. We can arrange to share the same lock, and if they’re in Java, then
they don’t expect closures. However, I’m trying to imagine what the
corresponding code looks like on the Java side. That is, the code that
does the moral equivalent of the above snippet. Everything I can think
of
seems incredibly verbose and annoying.
The two things I can think of are:
Build a Runnable to pass off to some lock-handling method. Bleah.
Put the lock-acquire and lock-release inline each time, with the
associated try/finally stuff. Bleah.
Perhaps I’m worrying too much. If they’re Java programmers, they’re
used
to writing incredibly verbose code, I suppose. Still I’m hoping that
you
know of some cleverness in Java that can help. Is there something neat
in
Java 7 that helps? Some clever use of introspection?
Think outside the box! Please, impress me with your Java-fu! :=)
From your Ruby code you would just pass a block, JRuby would convert it
to
an implementation of the appropriate interface. Your Java using friends
would need to do the normal work of implementing the interface (either
anonymously or more concretely). You’d need a Java class with a method
that did this locking work for you that took an instance of an interface
as
a parameter. Both Ruby and Java would then be able to use this pretty
seamlessly.
These are the kinds of things I’d considered in the “Build a Runable”
case.
However, this little pattern gets used in numerous places with small
snippets of code. Perhaps that’s my problem, and need to figure out how
to
make them more large-grained.
Thus, the Java overhead (in lines of code and annoyance) of building an
Anonymous class to arrange for a line of code to run under the lock
seems
onerous. Still, it appears that that’s what you’ve gotta do.
In Lenny’s example, for instance, you write ~5 lines of code to execute
one
under the lock. Perhaps I’ve been doing Ruby for too long for that to
seem
acceptable.
Build a Runnable to pass off to some lock-handling method. Bleah.
Put the lock-acquire and lock-release inline each time, with the associated
try/finally stuff. Bleah.
Perhaps I’m worrying too much. If they’re Java programmers, they’re used to
writing incredibly verbose code, I suppose. Still I’m hoping that you know of
some cleverness in Java that can help. Is there something neat in Java 7 that
helps? Some clever use of introspection?
Think outside the box! Please, impress me with your Java-fu! :=)
Cheers,
–Bob
We do similar stuff using an anonymous class implementation of a
callback interface in Java and a block based interface for ruby.