Double Check does work!

1 Comment

I was reading an interview with Josh Bloch about the 2nd edition of his great book Effective Java on Java.net yesterday and was pleasantly surprised to find out that if you use volatile within the Double Check pattern it is now safe in JDK 5 and above.  I did not know this, the rumor mill was that Double Check did not work even in JDK 5.  Here’s an example of Double Check.  Josh suggests that you copy it as is and make no modifications.

// Double-check idiom for lazy initialization of instance fields.
private volatile FieldType field;
FieldType getField() {
    FieldType result = field;
    if (result == null) { // First check (no locking)
        synchronized(this) {
            result = field;
            if (result == null) // Second check (with locking)
                field = result = computeFieldValue();
        }
    }
     return result;
}

Just this revelation alone makes me want to buy his book.  I wonder what other goodies are in there.  Seriously though, I’ve had need for the double-check pattern a lot over the years as avoiding synchronization can be the biggest scalability  increase in writing middleware.  I’m psyched that it actually works!

Idiocracy

Leave a comment

There’s three things in this presidential campaign that really made me burst out laughing when I heard them.  The first was when Vice Presidential candidate,  Sarah Palin said “Its time that normal Joe Six-pack American is finally represented in the position of vice presidency.”  Palin said if she and John McCain win, they will “put government back on the side of the people of Joe Six-pack like me.”  Do you know what the definition of Joe Six Pack is?  From the Urban Dictionary:

Average American moron, IQ 60, drinking beer, watching baseball and CNN, and believe everything his President says.

Beyond the fact that every time I hear Palin speak I think of the movie Fargo, why is this statement either appealing or reassuring to voters?  I never understood why many Americans feel they have to vote for somebody they’d feel most comfortable having a beer with or somebody “just like them”.

The second hilarious thing was when McCain started talking about Joe the Plumber.  “Joe I will fight for you.”  I was cracking up every time McCain mentioned him in the debate.  Here’s a man I actually switched parties in 2000 to vote for in the GOP primaries making a joke out of his campaign.  He feels he’s so behind in the polls he has to pull this kind of publicity stunt?  Sad, and actually quite hilarious at the same time.

The third and final belly burster is that “Joe the Plumber” is actually now campaigning for McCain in Ohio.  Who the F is this guy?  If you start reading about him you’ll find he actually isn’t really a licensed plumber and never completed the apprentice program for plumbing.  IMO, McCain should fire the campaign advisor who suggested to make Joe the Plumber a celebrity.  The guy is already stumbling and bumbling and making an ass out of himself and McCain.

All and all, this appealing to the lowest common denominator of society makes me want to secede from the Union too.  Many times I think Mike Judge got it right.

JAX-RS Multipart support with RESTEasy

7 Comments

I just finished implementing some “multipart/*” and multipart/form-data support within RESTEasy.  It will be out with the next release.  Highlights?

A JAX-RS compatable API

Our current support for multipart is through the MimeMultipart classes within the Java Mail library.  They are limited because they do not use the MessageBodyReader/Writers available in JAX-RS.  I have written two parallel APIs that provide multipart support in a JAX-RS way:

package org.jboss.resteasy.plugins.providers.multipart;

public interface MultipartInput {
   List<InputPart> getParts();
   String getPreamble();
}

public interface InputPart {
   MultivaluedMap<String, String> getHeaders();
   String getBodyAsString();
   <T> T getBody(Class<T> type, Type genericType) throws IOException;
   <T> T getBody(org.jboss.resteasy.util.GenericType<T> type) throws IOException;
   MediaType getMediaType();
}

MultipartInput is a simple interface that allows you to get access to each part of the multipart message. Each part is represented by an InputPart interface. Each part has a set of headers associated with it.  You can unmarshall the part by calling one of the getBody() methods. The Type genericType parameter can be null, but the Class type parameter must be set. Resteasy will find a MessageBodyReader based on the media type of the part as well as the type information you pass in. The following piece of code is unmarshalling parts which are XML into a JAXB annotated class called Customer.

   @Path("/multipart")
   public class MyService   {
      @PUT
      @Consumes("multipart/mixed")
      public void put(MultipartInput input)
      {
         List<Customer> customers = new ArrayList...;
         for (InputPart part : input.getParts())
         {
            Customer cust = part.getBody(Customer.class, null);
            customers.add(cust);
         }
      }
   }

There’s a similar API for outputing multipart.

Multipart with vanilla Lists and Maps

Another feature I’ve added is the ability to use regular instances of java.util.List(any multipart format) or Map (form-data only) to represent multipart data.  Its only usable when your parts are uniform though.

Here’s an example of using it:

parameter of the List type declaration. Here’s an example again of unmarshalling a list of customers.

   @Path("/multipart")
   public class MyService
   {
      @PUT
      @Consumes("multipart/mixed")
      public void put(List<Customer> customers)
      {
         ...
      }
   }

That’s using input.  The problem with output is that RESTEasy has no idea what mime type you want to marshal or List or Map into.  So, the @PartType annotation is used.  Here’s an example of outputing multipart/form-data with a map:

@Path("/multipart")
   public class MyService
   {
      @GET
      @Produces("multipart/form-data")
      @PartType("application/xml")
      public Map<String, Customer> get()
      {
         ...
      }

Multipart-Formdata with POJOs

Finally, I added the ability to map POJO form classes to multipart/form-data.  You re-use @FormParam on fields and/or properties of a user-provided POJO.  Here’s an example:

   public class CustomerProblemForm {
      @FormData("customer")
      @PartType("application/xml")
      private Customer customer;

      @FormData("problem")
      @PartType("text/plain")
      private String problem;

      public Customer getCustomer() { return customer; }
      public void setCustomer(Customer cust) { this.customer = cust; }
      public String getProblem() { return problem; }
      public void setProblem(String problem) { this.problem = problem; }
   }

After defining your POJO class you can then use it to represent multipart/form-data. Here’s an example of sending a CustomerProblemForm using the RESTEasy client framework

   @Path("portal")
   public interface CustomerPortal {

      @Path("issues/{id}")
      @Consumes("multipart/form-data")
      @PUT
      public void putProblem(@MultipartForm CustomerProblemForm,
                             @PathParam("id") int id);
   }

   {
       CustomerPortal portal = ProxyFactory.create(CustomerPortal.class, "http://example.com");
       CustomerProblemForm form = new CustomerProblemForm();
       form.setCustomer(...);
       form.setProblem(...);

       portal.putProblem(form, 333);
   }

You see that the @MultipartForm annotation was used to tell RESTEasy that the object has @FormParam and that it should be marshalled from that. You can also use the same object to receive multipart data. Here is an example of the server side counterpart of our customer portal.

   @Path("portal")
   public class CustomerPortalServer {

      @Path("issues/{id})
      @Consumes("multipart/form-data")
      @PUT
      public void putIssue(@MultipartForm CustoemrProblemForm,
                           @PathParm("id") int id) {
         ... write to database...
      }
   }

I need a new name for this blog

4 Comments

I enjoyed being “Angry Bill” for awhile, but I think it has run its course.  Really, its not because any grief I’ve got at Red Hat or within the Java community.  It all has to do with my family.  I actually get a lot of crap for “Angry Bill”.  My wife uses it to ridicule me.  My paranoid mother (you know how mothers are) thinks some crazy on the internet is going to take too much offense and seek to do me bodily harm.  When my wife and extended family started calling me “Angry Bill” instead of Bill, I knew it was time to make a change.

So, what to change it too?  Doing a play around Hani‘s nickname for me, Bill Berk, is a thought.  From wikipedia:

  • Berk, slang for an idiot
  • Berk, rhyming slang for Cunt

Idiot and Cunt pretty much sum up my major contributions to the open source Java community.  Yet, a play around Berk is still too much of the same thing as “Angry Bill” was already a metaphor for the same adjectives.  If you knew who The Real Angry Bill was you’d understand that I was making fun of myself by naming my blog “Angry Bill”.  Besides, I’m scared that people will actually start thinking my real name is Bill Berk and not Bill Burke.  Now that would be a catastrophe 😉

I could be really boring and name it “Burke Central, Bill Burke’s tech blog”.  Or maybe “Tech Tailgate”?  “Bill’s Blog” sounds kinda corny, but catchy.  Or how about “Mr. Bill‘s Blog, Oh Nooooo! Mr. Bill talks tech”

JAX-RS + Asynch HTTP

10 Comments

A RESTEasy user (and JBoss customer) asked about 6 weeks ago if we were planning on supporting Resteasy with Asynchronous HTTP.  For those of you not familiar with Asynchronous HTTP, take a look at Servlet 3.0, Tomcat Comet APIs, or Jetty’s continuations.  I decided to add some limited support after doing some research.

The primary (and IMO, the only) usecase for Asynchronous HTTP is in the case where the client is polling the server for a delayed response.  The usual example is an AJAX chat client where you want to push/pull from both the client and the server.  These scenarios have the client blocking a long time on the server’s socket waiting for a new message.  What happens in synchronous HTTP is that you end up having a thread consumed per client connection.  This eats up memory and valuable thread resources.  No such a big deal in 90% of applications, but when you start getting a lot of concurrent clients that are blocking like this, there’s a lot of wasted resources.

As for Resteasy and asynchronous HTTP, I don’t want to create a COMET server.  Maybe I’m totally wrong, but it seems that the idea of COMET is to use HTTP solely for the purpose of initiating a dedicated socket connection to your server.  After the initial connection is made, the client and server just tunnel their own message protocol across the socket for any number of requests.

Now, this isn’t necessarily a bad idea.  Its actually a good one for performance reasons.  As a JBossian David Lloyd explained to me in private email, what this API allows you to do is create a direct connection to your service so that you don’t have to redispatch with every message that is exchange from the client and server.  Sure, HTTP Keep Alive allows you to avoid re-establishing the socket connection, but you don’t have to worry about all the other path routing logic to get the message to the Java object that services the request.

Still, this is something I don’t want or need to provide through RESTEasy.  Its really using HTTP to tunnel a new protocol and something that is very unRESTful to me.  Basically it requires that the client knows how to communicate the COMET protocol, which IMO, makes ubiquity very hard.  Besidesk, Tomcat, JBoss Web, and Jetty will probably do a fine job here.  There are also already a number of COMET servers available on the web.  No, I will focus on giving asynchronous HTTP features to a pure HTTP and JAX-RS request.

What I will initially provide through RESTEasy is a very simple callback API.

@Path("/myresource")
@GET
public void getMyResource(@Suspend AsynchronousResponse response) {

   ... hand of response to another thread ...
}

public interface AsynchronousResponse {

   void setResponse(javax.ws.rs.core.Response response);

}

The @Suspend annotation tells Resteasy that the HTTP request/response should be detached from the currently executing thread and that the current thread should not try to automaticaly process the response.  The AsynchronousResponse is the callback object.  It is injected into the method by Resteasy.  Application code hands off the AsynchronousResponse to a different thread for processing.  The act of calling setResponse() will cause a response to be sent back to the client and will also terminate the HTTP request.

Servlet 3.0 has asynchronou APIs.  When you suspend a request, the request may be redelivered when a timeout occurs.  I don’t want to have a Resteasy replacement for these APIs.  What I want is something that complements these APIs and makes a specific usecase easier to write.  The use case I want to solve is detaching the processing of an HTTP response from the current thread of execution so that another thread can do the work when ready.  That’s it.  So, there will be no redelivery of a request.

Initially I plan to work with the asynchronous apis within the Tomcat 6.0 NIO transport as this is what is distributed with JBoss 4.2.3.  Next I plan to work with the JBoss Web asynchronous apis, then Jetty 6, then finally with a Servlet 3.0 implementation.

If you have any ideas on this subject, please let me know.  I can work them into the prototype I’m developing.

Atom too SOAPy for me

6 Comments

I’ve heard a lot of talk lately about using the Atom protocol for something other than a better RSS feed, like using it as a messaging protocol.  For instance, I was reading this excellent article on using REST to design a workflow on Infoq.com where they use the Atom format to describe and interact with a work queue.  The example was that a order fulfilment worker would the server and would get back an Atom feed of what jobs needed to be fulfilled.  Other, like James Strachan, had talked about using atom as well.

For me, the value of Atom haven’t really clicked with me yet.  Its just too SOAPy for me.  If you look at ATOM, the ATOM protocol, and how people are talking about using it, they’re really using it as an envelope.  One of the things that attracted me to REST was that I could focus on the problem at hand and ignore bulky middleware protocols (like SOAP) and lean on HTTP as a rich application protocol.

For example, if you want to get a list of messaging, why not just multipart/mixed?  Its a very simple format.  Its easy to parse.  You can assign specify headers to each body and use well-known headers like Content-Location if you want to replace actual content with a link. Its all much more compact.  Better yet, why not just send back a comma-delimited list of URLs.

Maybe I just haven’t seen the light yet.  It took me months to accept REST as a viable way of doing things.  Maybe I just need somebody to yell at me about ATOM.