Tuesday, July 13, 2010

Moderating Chinese comments

I've been rejecting comments in Chinese whenever I can't be sure that the comment isn't spam, i.e., always. Google Translate renders them as unobjectionable but content-free, but so far none of them seem to have come from an actual person who read my post.

If you can read my blog posts and you'd like to comment in Chinese, please include an English translation.

Monday, June 14, 2010

Google Collections is dead, long live Guava!

Kevin Bourrillion wants to get the word out: Google Collections is dead, long live Guava! Guava is a proper superset of Google Collections, so the passing of the latter is cause to rejoice, not mourn.

I've only scratched the surface of Guava in my own work on Seat Yourself, but I can tell already that it makes large parts of our "common" code unnecessary. Being able to replace your own code with a well-tested open source library is a wonderful thing, like getting someone else to mow the lawn for free.

In what feels to me like a dark time, as big companies privately negotiate the fate of Java and the JCP, Google's ongoing and generous investment in and championing of open Java-related technologies (Guava, GWT, GAE/J, Android, to name a few) is a welcome bright spot. Without their work ... well, I'd still be a Java developer, but I'd probably be looking for a way out.

That I'm still enthusiastic about coding in Java, in spite of the murky politics, is largely due to my friends at Google, which should tell you something.

Monday, May 24, 2010

The Minstrel Boy

The Minstrel Boy, a piece I wrote nearly 25 years ago during graduate work in Computer Science at Cornell (with a minor in Music Composition), received its first public performance yesterday at the Unitarian-Universalist Congregation at Shelter Rock. I had shown the score to the music director there, Stephen Michael Smith, who has a track record of fostering new works and composers, and to my surprise and pleasure, he very quickly arranged for a group of singers—Leslie Craigie, Farah Chandu, Leslie Pirchinello, Chee Shun Tan, and Brace Negron—to perform it as part of the regular Sunday service. (Pianists Evan Solomon and Akira Eguchi assisted during rehearsals.)

The piece is a setting for SSATB (with solo sections) of Thomas Moore's poem of the same name. It's normally sung to the tune of "The Moreen", and I used that melody heavily in my setting. The composition teacher under whose supervision I wrote it, Steven Stucky, was not, I think, entirely on board with my wholesale appropriation of these existing materials—he might reasonably have felt that I should be producing my own music instead of rehashing others', at least on his watch—but I persisted anyway.

This was the second world premiere of my work in as many months: In April, TracyLynn Conner performed a song I wrote for her, as part of a American Cancer Society benefit concert.

Both of these events were big thrills for me. If you don't count my music for theater, arrangements, orchestrations, or works for personal occasions, the last time I had a world premiere was in ... 1984.

Friday, November 27, 2009

Concurrently initialized singletons in Guice

William Pietri asked whether it would be possible to take advantage of concurrency and Guice's knowledge of dependencies to provide interdependent (and expensive to create) singleton services in parallel.
For example, say that service A depends on services B and C and that B and C don't know about each other (and so could be constructed concurrently). Obviously, you could explicitly construct B and C in separate tasks running in a thread pool, then construct A once B and C exist.
class A {
    A(B b, C c) { /* ... use b and c ... */ }
}

class B {
    B() { /* ... takes a long time ... */ }
}

class C {
    C() { /* ... takes a long time ... */ }
}

class Services {
    A a; B b; C c;
    void init() throws InterruptedException {
        final CountDownLatch ready = new CountDownLatch(2);
        Executor pool = Executors.newCachedThreadPool();
        pool.execute(new Runnable() {
            public void run() { b = new B(); ready.countDown(); }
        })
        pool.execute(new Runnable() {
            public void run() { c = new C(); ready.countDown(); }
        })
        ready.await();
        a = new A(b, c);
        // Now publish a, b, and c safely -- not shown.
    }
}
But it's a pain to have to orchestrate this yourself. You have to know the dependencies intimately and write a lot of tricky code. If the dependencies change, the code has to be completely rethought. Wouldn't it be nice if Guice could do this for you automatically without giving up on the opportunities for concurrency? Well, it turns out that it can.
The idea is to use a variant of singleton scope that runs the providers of all bindings for that scope in separate threads. Naturally some of these providers block in their own thread while their dependencies finish in other threads, but those services that can be constructed in parallel will be.
Here's what the Guice version looks like:
@ConcurrentSingleton
class A {
    @Inject A(B b, C c) { /* ... use b and c ... */ }
}

@ConcurrentSingleton
class B {
    @Inject B() { /* ... takes a long time ... */ }
}

@ConcurrentSingleton
class C {
    @Inject C() { /* ... takes a long time ... */ }
}
No special initialization code needed, just inject A, B, and C wherever they are needed. (Note that if you have circular dependencies, this probably won't work. So don't have circular dependencies.)
ConcurrentSingleton is just a scope annotation. The actual scope implementation is ConcurrentSingletonScope. I have a fleshed-out version of the A, B, C example, ConcurrentSingletonExample, that is slightly different from the code above; it uses Providers for B and C so that A can do some work before getting B and C in the constructor.
You aren't forced to do all the expensive work in the constructor. You could also inject a start method with injected parameters to provide needed dependencies.
In the same thread that provoked the ConcurrentSingleton response, Jesse Wilson suggested the use of the experimental lifecycle facility in Guava. This could prove useful in the current context if, for example, you have singleton services that take a while to stop and could benefit from being stopped in parallel.

Update 2009-11-30

I added a call to pool.shutdown() in the scope implementation to make sure the pool threads don't prevent the JVM from exiting. It might not be necessary, but I don't think it hurts.

Update 2010-7-3

Added explicit notice that the sources are in the public domain.

Update 2018-10-16

Added a GitHub repository with the concurrent singleton code and other utilities, as the old links to code weren't working any more. Now using MIT open source license.

Monday, October 26, 2009

The Emperor's New Clothes

I posted Ray Mason's video of The Emperor's New Clothes, a Theatre Three Children's Theatre production of a show that Jeff Sanzel and I wrote together, on my Facebook profile and my YouTube channel, broken up into scene length segments.

See the links section in the right-hand column -- you'll want to look at the YouTube version unless you're my Facebook friend, and even then you might prefer to watch the YouTube playlist, something for which there is no analogue in Facebook ... is there?

I haven't bothered to post to MySpace this time around.

Friday, September 11, 2009

Joshua Rosenblum's site

Josh Rosenblum has a website worth checking out:

http://rosenblummusic.com

The site was designed and implemented by Josh's 13-year-old son, Julian.

And don't be afraid to go ahead and buy those albums! :-)

Tuesday, May 12, 2009

Dependency injection in Restlet 2.0 with Guice

I'm very excited about Restlet 2.0, which is in testing now and scheduled for release at the end of 2009. Among other things, the newly refactored Resource API encourages more readable code through the use of a small number of annotations. Here's a very simple server-side resource:
public class DefaultResource extends ServerResource {
    @Get public String represent() {
        return "Default resource, try /hello/resource or /hello/handler";
    }
}

ServerResource has a no-arg constructor, so you don't need to pass Context, Request, and Response objects to super().

Nice as this is, I still want to inject my resources using Guice, so I've updated the Restlet-Guice classes from my previous post to support both the new ServerResources and the old Handlers. It incorporates the enhancement mentioned in the updates: You can override methods to use different providers for Application, Context, Request, and Response, although for most purposes the default providers should suffice.

Update 2009-Dec-11


I've been working on a Guice extension for Restlet as an incubator project that uses the ideas in this posting. My goal is to make this extension independent of Guice at the interface level, so that people can provide implementations for different DI frameworks, of which Guice is only the first.

Monday, December 15, 2008

Musical numbers from my shows

After years of vague promises to cast members to provide a record of the shows that Jeff Sanzel and I have written together for Theatre Three children's theatre productions, I finally got up my courage to edit together the tapes I'd made into more or less coherent individual musical numbers. I've been posting them to YouTube, Facebook, and MySpace as I finish them.

The tapes were made by setting up a camera (or two) before each performance, pointing it towards the stage, turning it on, and leaving it there unattended. In some cases I also recorded a separate audio track with a decent stereo mic. There are several problems with this approach:
  • The camera is stationary, so any zooming or panning has to be applied after the fact. This makes for blurry closeups.

  • The autofocus is often confused by stage lighting changes.

  • Each performance is slightly different, so synching lip movements can be tricky. I got it wrong in several instances.

  • The mic in the camera is not as good as the separate stereo mic, and the sound quality varies depending on where the camera is placed. So only The Fairy Princess has good sound.

But I hope the end results are entertaining, if only for the performers who took part in the productions.

Eventually I'd like to create a video or sequence of videos covering an entire show, for watching in a YouTube playlist, for example. I made studio recordings of Hansel and Gretel and The Fairy Princess (and I hope to do so for The Elves and the Shoemaker), so it is possible that I could use that material for the soundtrack.

Thursday, September 25, 2008

New CD: "Colloquy"

I am once more proud to announce the release of a CD that I produced: Colloquy, an album of music by Gary William Friedman. And once more, I am several weeks late in my announcement. Maybe I planned it that way. Yeah, that's it.

I wrote the liner notes for this album, and I won't repeat them here, so go get a copy and read them. Or don't read them, just listen to the music -- I don't mind.

Update:

There's also a video about the making of one of the pieces on the album.

Thursday, July 24, 2008

New CD: "Before Love Has Gone"

I'm proud to announce the release, one month ago, of a new album from Stevie Holland, Before Love Has Gone, that I co-produced with Todd Barkan and Gary William Friedman. (The actual release date was June 24, but I kept forgetting to blog about it and decided to wait out the full month.)

Go get it and listen to it. The whole album is great, but if you're really stingy and can only spring for one tune, I recommend "Lazy Afternoon". It's phenomenal.

Update:

There's also an EPK for the album.

Resource dependency injection in Restlet via Guice

(See a more recent posting on this subject.)

I have a body of code that already benefits from Guice dependency injection, and I want to migrate it from a servlet-based architecture to Restlet without losing those benefits. I've had some success, and I figured I'd report on it.

I don't mean that I wanted to use Guice to wire up an object graph of Restlets (Components, VirtualHosts, Applications, etc.). It's straightforward enough to use the builder-like API of Restlet, and such code is nicely confined in a few places where it doesn't bother the meat of the application, its resources.

What I do want is to have those resources created by Guice, so that they can be constructed with dependencies injected into them. With the Finder approach, resource constructors get a Context, a Request, and a Response, but that's it. I suppose I could find a way to stash an Injector in one of these so that resources could look up the dependencies they need, but I wanted something more direct. I came up with the following scheme, which seems to be working pretty well:

I use a custom Finder that knows how to look up a Handler/Resource by class or Guice key -- instances of these custom Finders are provided by a FinderFactory:
public interface FinderFactory {
    Finder finderFor(Key<? extends Handler> key);
    Finder finderFor(Class<? extends Handler> cls);
}

The class RestletGuice has static methods named createInjector that parallel those of the Guice class. The difference is that it adds bindings for Context, Request, Response, and FinderFactory. In my Guiced version of the FirstStepsApplication from restlet.org, the following lines create an Injector with some bindings and then look up the FinderFactory that will produce Finders that will be able to make use of those bindings. (These bindings are not necessarily good practice; they just demonstrate the technique.)
    Injector injector = RestletGuice.createInjector(new AbstractModule() {
        public void configure() {
            bind(Handler.class)
                .annotatedWith(HelloWorld.class)
                .to(HelloWorldResource.class);
            bindConstant()
                .annotatedWith(named(HelloWorldResource.HELLO_MSG))
                .to("Hello, Restlet-Guice!");
        }
    });
    FinderFactory factory = injector.getInstance(FinderFactory.class);

HelloWorldResource is slightly changed. It has a private final field, msg, that is used to generate the text representation. The msg field is initialized via an injected value.
    @Inject public HelloWorldResource(@Named(HELLO_MSG) String msg,
                                      Request request,
                                      Response response,
                                      Context context) {
        super(context, request, response);
        this.msg = msg;
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }
    static final String HELLO_MSG = "hello.message";

This all comes together in the Application class when attaching a Finder for the default routing.
    Finder finder = factory.finderFor(Key.get(Handler.class, HelloWorld.class));
    Router router = new Router(getContext());
    router.attachDefault(finder);
    return router;

I read this as "Route any request for this application to whatever resource is bound to @HelloWorld-annotated Handlers, injecting that resource's dependencies," which was exactly what I wanted.

For those who don't want to have to call a special RestletGuice method, there is a public class FinderFactoryModule extending AbstractModule that can be used with Guice.createInjector(...) to get the same effect.

FinderFactoryModule also implements FinderFactory, so you can construct an instance in your Restlet wiring code and use it right away. You can then use the FinderFactoryModule to create an injector explicitly.

As a special convenience, if you don't use a FinderFactoryModule to create an injector, one will be created implicitly the first time one of its Finders is used to find a target Handler/Resource. This encourages a style where each Application gets its own implicit Injector by creating a local FinderFactoryModule and using it to create Finders.

That's basically it. It works with plain Guice 1.0 and Restlet 1.1 (since it uses Handler as the base type for all Resources). I haven't had time to package it nicely, but you can follow the links below for the actual code.

Sources (links are out of date, use this instead):
FinderFactory.java
FinderFactoryModule.java
RestletGuice.java

Example (links are out of date, use this instead):
FirstStepsApplication.java
HelloWorld.java
HelloWorldResource.java
Main.java

Update (August 2008)


Chris Lee discovered that Context.getCurrent() doesn't work reliably as of 1.1m5; the workaround is to use Application.getCurrent().getContext(). A more comprehensive fix, that I hope to post soon, would involve letting subclasses of FinderFactoryModule override the methods that create the Providers for Request, Response, and Context.

Update (2009-Feb-3)


Leigh Klotz has a workaround for using Guice Finders with WadlApplication. And I still haven't had time to package any of this more nicely. (Feb 7: Jérôme Louvel took Leigh's suggestion and checked it in on the Restlet trunk.)

Tuesday, April 22, 2008

Concert at Kosciuszko Hall

I attended a lovely concert at Kosciuszko Hall in Manhattan on Monday night. Cellist Mairi Dorman-Phaneuf and composer-pianist Joshua Rosenblum performed works by Schumann, Brahms, de Falla, Prokofieff, Rosenblum, Bolling, and others, assisted by soprano Joanne Lessner, bassist Bill Ellison, drummer Bruce Doctor, and special guest Julia Murney.

Mairi's particular interest (she referred to it as an obsession) is in performing songs with the cello taking the voice part, and she made a compelling case for her obsession in the songs of Schumann, Brahms, and de Falla. I particularly liked Brahms' Wie Melodien.

The concert included the world premiere of Josh Rosenblum's setting for soprano, cello, piano, and contrabass of T. S. Eliot's poem, The Love Song of J. Alfred Prufrock. I liked it a lot, and I hope to make a recording of it soon so it can be shared with others.

I was very pleased to see that the three CDs on sale in the lobby were all produced (or co-produced) by me! Not surprising, of course, because they all feature Josh Rosenblum's music:There is another Peierls-produced Rosenblum album, Impetuosities, but it wasn't on sale at the concert.

Another world premiere of Josh's music can be heard at the upcoming performance of the dance company, The Chase Brock Experience. Chase Brock commissioned a ballet from Josh, and I produced a recording of the piece for use during the performance. It's called ... are you ready? ... Cut to the Chase.

Saturday, February 02, 2008

Magic in the City

If you're looking to hire a magician for a New York City area children's birthday party, Jazzo the Great comes highly recommended:

Card Riffle

Wednesday, January 16, 2008

Monday, November 05, 2007

Concurrency issues in Restlet

Issue #368 in the Restlet issue tracker was originally focused on the Guard class. Since then, I've taken a look at the rest of the org.restlet package and found that the fields of most classes are accessed without appropriate synchronization. [Update 2008-Feb-6: All of these have been fixed as of Restlet 1.1 M1.]

Most of these problems would disappear if the fields could be final, but that would mean taking away setter-injectability.

There is hope, however: Methods that are used only for setter injection (and not, for example, used to reconfigure an instance dynamically), should be documented as setter-injection-only, meaning they must not be called after the instance has been (safely) published. Fields set by such methods get their values before publication, and those values never change; such fields are effectively immutable. I don't know of any standard documentation conventions for this, but the important thing is to decide for each non-final, non-volatile field whether it is truly mutable or only setter-injected before publication.

I have a long-standing gripe about the Spring documentation that it doesn't state, at least not in terms that I recognize, under what conditions beans are safely published. The vanilla use cases (standard ApplicationContext implementations) are almost certainly fine, but if you have any doubts about whether your dependency injection framework can guarantee safe publication, then you should either guard your setter-injected fields with a lock or make them volatile. I have a personal preference for using volatile in this case, but most of my Java Concurrency in Practice co-authors have the opposite preference.

Even if you're fairly confident about your DI framework's guarantees, it is never wrong to guard field access or make a field volatile, only potentially wasteful. For a framework like Restlet that should be usable in any DI context, I think it would be prudent to assume the worst of that context.

But is setter injection really necessary? Most of the injected fields are of distinct types, so constructor injection in Spring would be straightforward. Getting rid of setter injection entirely would allow most, if not all, fields to be final, which would greatly reduce the risk of concurrency problems in Restlet.

Saturday, October 13, 2007

Babel

Jeffrey Sanzel writes (referring to this posting):

Here are the words I understood on your blog:

blog
Tim
Peierls (to an extent)
A (in context)
of (in context)
There
All

Tuesday, October 09, 2007

Basic rules for @ThreadSafe classes

Some rules for classes to be annotated with @ThreadSafe:
  1. All non-final, non-volatile fields (and final references to non-thread-safe state) must be annotated with @GuardedBy(x), where x is usually this, meaning that all access to the field -- reads and writes -- is performed within a synchronized (this) block or synchronized method. [This is probably the hardest rule for people to accept; it's not intuitive that reads must be performed with a lock held. See amplification below.]

  2. If two fields annotated with @GuardedBy participate in the same class invariant, they must be annotated with the same argument to @GuardedBy. [This is trivially satisfied if you only use @GuardedBy("this").]

  3. All compound actions with atomic semantics (e.g., check-then-act and read-modify-write sequences) must be performed completely within a synchronized block or method. [This is what many people incorrectly think is the only reason to use synchronized.]

  4. Do not make calls to code whose synchronization properties you don't know or control from inside a synchronized block or method; prefer open calls (calls made with no locks held). [This is a strategy for deadlock avoidance.]

  5. Prefer final fields. For collection fields, prefer thread-safe collections. (But don't bother using a thread-safe collection if the field needs to be @GuardedBy for some other reason.)

  6. Prefer final atomic variables to volatiles. Volatile fields cannot be modified atomically without a synchronized block.

  7. There need be no special relationship between x and y in "@GuardedBy(x) Type y;" as long as all access to y is made while holding x's lock.

  8. Don't be too clever: even if your clever reasoning is correct right now, it will be harder in the future for others (and you) to understand and maintain the code that relies on that reasoning.

Amplification


Brian Goetz suggests that I make this point more strongly: Not only do you need to declare such fields @GuardedBy(lock), you have to acquire lock every time you access the field in any way.

Concurrency discussion in Restlet community

I started a thread on concurrency issues in the Restlet framework, and it led to a several people saying nice things about Java Concurrency in Practice.

Jérôme Louvel's responsiveness to these issues is gratifying. A far cry from the huffiness I provoked when I had the temerity to question the concurrency guarantees in Spring!

Sunday, September 16, 2007

Java Concurrency in Practice news

I'm told that Java Concurrency in Practice is going into its fifth printing!

Custom Matcher and MethodInterceptor for DWR-Guice

I wanted a way to intercept calls to public methods of a remoted interface so I could replace my use of bindFilter with bindInterceptor, as described in an earlier posting.

At first I thought I could just use the static methods in Matchers:

bindInterceptor(
only(MyService.class),
any(),
myInterceptor
);

This doesn't intercept anything, because MyService is an interface. What I needed was to intercept calls to a method of a subclass of MyService for which there exists a method of the same name and argument types in MyService.

bindInterceptor(
subclassesOf(MyService.class),
declaredBy(MyService.class),
myInterceptor
);

The subclassesOf matcher is already provided in com.google.inject.matcher.Matchers, but I had to roll my own declaredBy method matcher. Here's the heart of the implementation (cls is a final Class<?> field, initialized from the argument to declaredBy):

public boolean matches(Method method) {
try {
// Matches if the method is from a subclass
// of the given class (or the class itself)
// and the given class declares a method
// with the same name and parameter types.
if (cls.isAssignableFrom(
method.getDeclaringClass())) {
// Return value of getDeclaredMethod
// is ignored. It throws an exception
// if the method is not found.
cls.getDeclaredMethod(
method.getName(),
method.getParameterTypes());
return true;
}
// fall through
} catch (NoSuchMethodException e) {
// fall through
} catch (SecurityException e) {
// fall through
}
return false;
}

This still didn't work quite right; the implementation of one method called another public method of the interface, and that call was intercepted even though it wasn't a remote call. To mimic AjaxFilter, I want to able to intercept only the outermost call. I wrote a MethodInterceptor-decorator:

public class OutermostCallInterceptor
implements MethodInterceptor {
/**
* Decorates a MethodInterceptor so that only the
* outermost invocation using that interceptor will
* be intercepted and nested invocations willbe
* ignored.
*/
public static MethodInterceptor outermostCall(
MethodInterceptor interceptor) {
return new OutermostCallInterceptor(interceptor);
}

/** Ensure underlying interceptor is injected. */
@Inject void injectInterceptor(Injector injector) {
injector.injectMembers(interceptor);
}

public Object invoke(MethodInvocation invocation)
throws Throwable {
int savedCount = count.get();
count.set(savedCount + 1);
try {
if (count.get() > 1)
return invocation.proceed();
else
return interceptor.invoke(invocation);
} finally {
count.set(savedCount);
}
}

private OutermostCallInterceptor(
MethodInterceptor interceptor) {
this.interceptor = interceptor;
}

private final MethodInterceptor interceptor;

private final ThreadLocal count =
new ThreadLocal() {
@Override protected Integer initialValue() {
return 0;
}
};
}

So now my binding looks like this:

bindInterceptor(
subclassesOf(MyService.class),
declaredBy(MyService.class),
outermostCall(myInterceptor)
);

and myInterceptor is injected. It's not as compact as using bindFilter, but I can apply multiple interceptors without having to resort to FluentConfigurator. The use of subclassesOf is probably redundant, since declaredBy checks that the method is from a subclass of MyService, but I think it helps to clarify what's going on.