Monday, December 13, 2010

What does Spring do?

Spring provides a lot of functionality, so I'll quickly review each major area
in turn.

Mission statement
Firstly, let's be clear on Spring's scope. Although Spring covers a lot of
ground, we have a clear vision as to what it should and shouldn't address.

Spring's main aim is to make J2EE easier to use and promote good programming
practice. It does this by enabling a POJO-based programming model that is
applicable in a wide range of environments.

Spring does not reinvent the wheel. Thus you'll find no logging
packages in Spring, no connection pools, no distributed transaction
coordinator. All these things are provided by open source projects (such as
Commons Logging, which we use for all our log output, or Commons DBCP), or by
your application server. For the same reason, we don't provide an O/R mapping
layer. There are good solutions to this problem such as TopLink, Hibernate and
JDO.

Spring does aim to make existing technologies easier to use. For example,
although we are not in the business of low-level transaction coordination, we
do provide an abstraction layer over JTA or any other transaction strategy.

Spring doesn't directly compete with other open source projects unless we feel
we can provide something new. For example, like many developers, we have never
been happy with Struts, and felt that there was room for improvement in MVC
web frameworks. (With Spring MVC adoption growing rapidly, it seems that many
agree with us.) In some areas, such as its lightweight IoC container and AOP
framework, Spring does have direct competition, but Spring was a pioneer in
those areas.

Spring benefits from internal consistency. All the developers are singing from
the same hymn sheet, the fundamental ideas remaining faithful to those of
Expert One-on-One J2EE Design and Development. And we've been able to
use some central concepts, such as Inversion of Control, across multiple
areas.

Spring is portable between application servers. Of course ensuring portability
is always a challenge, but we avoid anything platform-specific or non-standard
in the developer's view, and support users on WebLogic, Tomcat, Resin, JBoss,
Jetty, Geronimo, WebSphere and other application servers. Spring's
non-invasive, POJO, approach enables us to take advantage of
environment-specific features without sacrificing portability, as in the case
of enhanced WebLogic transaction management functionality in Spring 1.2 that
uses BEA proprietary APIs under the covers.

Inversion of control container
The core of Spring is the org.springframework.beans package, designed for working with JavaBeans.
This package typically isn't used directly by users, but underpins much Spring
functionality.

The next higher layer of abstraction is the bean factory. A Spring bean
factory is a generic factory that enables objects to be retrieved by name, and
which can manage relationships between objects.

Bean factories support two modes of object:

  • Singleton: in this case, there's one shared instance of the object
    with a particular name, which will be retrieved on lookup. This is the
    default, and most often used, mode. It's ideal for stateless service
    objects.
  • Prototype or non-singleton: in this case, each retrieval will result
    in the creation of an independent object. For example, this could be used to
    allow each caller to have its own distinct object reference.
Because the Spring container manages relationships between objects, it can add
value where necessary through services such as transparent pooling for managed
POJOs, and support for hot swapping, where the container introduces a level of
indirection that allows the target of a reference to be swapped at runtime
without affecting callers and without loss of thread safety. One of the
beauties of Dependency Injection (discussed shortly) is that all this is
possible transparently, with no API involved.

As org.springframework.beans.factory.BeanFactory is a simple interface, it can be implemented in different ways. The BeanDefinitionReader
interface separates the metadata format from BeanFactory implementations themselves,
so the generic BeanFactory implementations Spring provides can be used with different
types of metadata. You could easily implement your own BeanFactory or
BeanDefinitionReader, although few users find a need to. The most commonly
used BeanFactory definitions are:

  • XmlBeanFactory. This parses a simple, intuitive XML structure defining the classes and
    properties of named objects. We provide a DTD to make authoring easier.
  • DefaultListableBeanFactory: This provides the ability to parse bean definitions in properties
    files, and create BeanFactories programmatically.
Each bean definition can be a POJO (defined by class name and JavaBean
initialisation properties or constructor arguments), or a FactoryBean. The FactoryBean
interface adds a level of indirection. Typically this is used to create
proxied objects using AOP or other approaches: for example, proxies that add
declarative transaction management. This is conceptually similar to EJB
interception, but works out much simpler in practice, and is more powerful.

BeanFactories can optionally participate in a hierarchy, "inheriting"
definitions from their ancestors. This enables the sharing of common
configuration across a whole application, while individual resources such as
controller servlets also have their own independent set of objects.

This motivation for the use of JavaBeans is described in Chapter 4 of
Expert One-on-One J2EE Design and Development, which is available on
the ServerSide as a free PDF
(/articles/article.tss?l=RodJohnsonInterview).

Through its bean factory concept, Spring is an Inversion of Control
container. (I don't much like the term container, as it conjures up
visions of heavyweight containers such as EJB containers. A Spring BeanFactory
is a container that can be created in a single line of code, and requires no
special deployment steps.) Spring is most closely identified with a flavor of
Inversion of Control known as Dependency Injection--a name coined by
Martin Fowler, Rod Johnson and the PicoContainer team in late 2003.

The concept behind Inversion of Control is often expressed in the Hollywood
Principle
: "Don't call me, I'll call you." IoC moves the responsibility
for making things happen into the framework, and away from application code.
Whereas your code calls a traditional class library, an IoC framework calls
your code. Lifecycle callbacks in many APIs, such as the setSessionContext() method for
session EJBs, demonstrate this approach.

Dependency Injection is a form of IoC that removes explicit dependence on
container APIs; ordinary Java methods are used to inject dependencies
such as collaborating objects or configuration values into application object
instances. Where configuration is concerned this means that while in
traditional container architectures such as EJB, a component might call the
container to say "where's object X, which I need to do my work", with
Dependency Injection the container figures out that the component needs
an X object, and provides it to it at runtime. The container does this
figuring out based on method signatures (usually JavaBean properties or
constructors) and, possibly, configuration data such as XML.

The two major flavors of Dependency Injection are Setter Injection
(injection via JavaBean setters); and Constructor Injection (injection
via constructor arguments). Spring provides sophisticated support for both,
and even allows you to mix the two when configuring the one object.

As well as supporting all forms of Dependency Injection, Spring also provides
a range of callback events, and an API for traditional lookup where necessary.
However, we recommend a pure Dependency Injection approach in general.

Dependency Injection has several important benefits. For example:

  • Because components don't need to look up collaborators at runtime, they're
    much simpler to write and maintain. In Spring's version of IoC, components
    express their dependency on other components via exposing JavaBean setter
    methods or through constructor arguments. The EJB equivalent would be a JNDI
    lookup, which requires the developer to write code that makes environmental
    assumptions.
  • For the same reasons, application code is much easier to test. For example,
    JavaBean properties are simple, core Java and easy to test: simply write a
    self-contained JUnit test method that creates the object and sets the
    relevant properties.
  • A good IoC implementation preserves strong typing. If you need to use a
    generic factory to look up collaborators, you have to cast the results to
    the desired type. This isn't a major problem, but it is inelegant. With IoC
    you express strongly typed dependencies in your code and the framework is
    responsible for type casts. This means that type mismatches will be raised
    as errors when the framework configures the application; you don't have to
    worry about class cast exceptions in your code.
  • Dependencies are explicit. For example, if an application class tries to
    load a properties file or connect to a database on instantiation, the
    environmental assumptions may not be obvious without reading the code
    (complicating testing and reducing deployment flexibility). With a
    Dependency Injection approach, dependencies are explicit, and evident in
    constructor or JavaBean properties.
  • Most business objects don't depend on IoC container APIs. This makes it easy
    to use legacy code, and easy to use objects either inside or outside the IoC
    container. For example, Spring users often configure the Jakarta Commons
    DBCP DataSource as a Spring bean: there's no need to write any custom code
    to do this. We say that an IoC container isn't invasive: using it
    won't invade your code with dependency on its APIs. Almost any POJO can
    become a component in a Spring bean factory. Existing JavaBeans or objects
    with multi-argument constructors work particularly well, but Spring also
    provides unique support for instantiating objects from static factory
    methods or even methods on other objects managed by the IoC container.
This last point deserves emphasis. Dependency Injection is unlike traditional
container architectures, such as EJB, in this minimization of dependency of
application code on container. This means that your business objects can
potentially be run in different Dependency Injection frameworks - or outside
any framework - without code changes.

In my experience and that of Spring users, it's hard to overemphasize the
benefits that IoC--and, especially, Dependency Injection--brings to
application code.

Dependency Injection is not a new concept, although it's only recently made
prime time in the J2EE community. There are alternative DI containers:
notably, PicoContainer and HiveMind. PicoContainer is particularly lightweight
and emphasizes the expression of dependencies through constructors rather than
JavaBean properties. It does not use metadata outside Java code, which limits
its functionality in comparison with Spring. HiveMind is conceptually more
similar to Spring (also aiming at more than just IoC), although it lacks the
comprehensive scope of the Spring project or the same scale of user community.
EJB 3.0 will provide a basic DI capability as well.

Spring BeanFactories are very lightweight. Users have successfully used them
inside applets, as well as standalone Swing applications. (They also work fine
within an EJB container.) There are no special deployment steps and no
detectable startup time associated with the container itself (although certain
objects configured by the container may of course take time to initialize).
This ability to instantiate a container almost instantly in any tier of an
application can be very valuable.

The Spring BeanFactory concept is used throughout Spring, and is a key reason
that Spring is so internally consistent. Spring is also unique among IoC
containers in that it uses IoC as a basic concept throughout a full-featured
framework.

Most importantly for application developers, one or more BeanFactories provide
a well-defined layer of business objects. This is analogous to, but much
simpler (yet more powerful), than a layer of local session beans. Unlike EJBs,
the objects in this layer can be interrelated, and their relationships managed
by the owning factory. Having a well-defined layer of business objects is very
important to a successful architecture.

A Spring ApplicationContext is a subinterface of BeanFactory, which provides
support for:

  • Message lookup, supporting internationalization
  • An eventing mechanism, allowing application objects to publish and
    optionally register to be notified of events
  • Automatic recognition of special application-specific or generic bean
    definitions that customize container behavior
  • Portable file and resource access
XmlBeanFactory example
Spring users normally configure their applications in XML "bean definition"
files. The root of a Spring XML bean definition document is a <beans> element. The
<beans> element contains one or more <bean> definitions. We normally specify the
class and properties of each bean definition. We must also specify the id,
which will be the name that we'll use this bean with in our code.

Let's look at a simple example, which configures three application objects
with relationships commonly seen in J2EE applications:

  • A J2EE DataSource
  • A DAO that uses the DataSource
  • A business object that uses the DAO in the course of its work
In the following example, we use a BasicDataSource from the Jakarta Commons DBCP project.
(ComboPooledDataSource from the C3PO project is also an excellent option.) BasicDataSource, like many other
existing classes, can easily be used in a Spring bean factory, as it offers
JavaBean-style configuration. The close method that needs to be called on
shutdown can be registered via Spring's "destroy-method" attribute, to avoid
the need for BasicDataSource to implement any Spring interface.

<beans>

  <bean id="myDataSource"
 class="org.apache.commons.dbcp.BasicDataSource"
 destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/mydb" />
    <property name="username" value="someone" />
  </bean>
All the properties of BasicDataSource we're interested in are Strings, so we specify their
values with the "value" attribute. (This shortcut was introduced in Spring
1.2. It's a convenient alternative to the <value> subelement, which is usable even
for values that are problematic in XML attributes.) Spring uses the standard
JavaBean PropertyEditor mechanism to convert String representations to other
types if necessary.

Now we define the DAO, which has a bean reference to the DataSource.
Relationships between beans are specified using the "ref" attribute or <ref>
element:

<bean id="exampleDataAccessObject"
  class="example.ExampleDataAccessObject">
    <property name="dataSource" ref="myDataSource" />
  </bean>
The business object has a reference to the DAO, and an int property
(exampleParam). In this case, I've used the subelement syntax familiar to
those who've used Spring prior to 1.2:

<bean id="exampleBusinessObject"
  class="example.ExampleBusinessObject">
    <property name="dataAccessObject"><ref bean="exampleDataAccessObject"/></property>
    <property name="exampleParam"><value>10</value></property>
  </bean>

</beans>
Relationships between objects are normally set explicitly in configuration, as
in this example. We consider this to be a Good Thing in most cases. However,
Spring also provides what we call "autowire" support, where it figures out the
dependencies between beans. The limitation with this - as with PicoContainer -
is that if there are multiple beans of a particular type it's impossible to
work out which instance a dependency of that type should be resolved to. On
the positive side, unsatisfied dependencies can be caught when the factory is
initialized. (Spring also offers an optional dependency check for explicit
configuration, which can achieve this goal.)

We could use the autowire feature as follows in the above example, if we
didn't want to code these relationships explicitly:

<bean id="exampleBusinessObject"
 class="example.ExampleBusinessObject"
 autowire="byType">

    <property name="exampleParam" value="10" />
 </bean>
With this usage, Spring will work out that the dataSource property of
exampleBusinessObject should be set to the implementation of DataSource it
finds in the present BeanFactory. It's an error if there is none, or more than
one, bean of the required type in the present BeanFactory. We still need to
set the exampleParam property, as it's not a reference.

Autowire support has the advantage of reducing the volume of configuration. It
also means that the container can learn about application structure using
reflection, so if you add an additional constructor argument of JavaBean
property, it may be successfully populated without any need to change
configuration. The tradeoffs around autowiring need to be evaluated carefully.

Externalizing relationships from Java code has an enormous benefit over hard
coding it, as it's possible to change the XML file without changing a line of
Java code. For example, we could simply change the myDataSource bean definition to
refer to a different bean class to use an alternative connection pool, or a
test data source. We could use Spring's JNDI location FactoryBean to get a
datasource from an application server in a single alternative XML stanza, as
follows. There would be no impact on Java code or any other bean definitions.

<bean id="myDataSource"
 class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="jdbc/myDataSource" />
  </bean>
Now let's look at the Java code for the example business object. Note that
there are no Spring dependencies in the code listing below. Unlike an EJB
container, a Spring BeanFactory is not invasive: you don't normally need to
code awareness of it into application objects.

public class ExampleBusinessObject implements MyBusinessObject {

 private ExampleDataAccessObject dao;
 private int exampleParam;

 public void setDataAccessObject(ExampleDataAccessObject dao) {
  this.dao = dao;
 }

 public void setExampleParam(int exampleParam) {
  this.exampleParam = exampleParam;
 }

 public void myBusinessMethod() {
  // do stuff using dao
 }
}
Note the property setters, which correspond to the XML references in the bean
definition document. These are invoked by Spring before the object is used.

Such application beans do not need to depend on Spring: They don't need to
implement any Spring interfaces or extend Spring classes: they just need to
observe JavaBeans naming convention. Reusing one outside of a Spring
application context is easy, for example in a test environment. Just
instantiate it with its default constructor, and set its properties manually,
via setDataSource() and setExampleParam() calls. So long as you have a no-args constructor, you're free
to define other constructors taking multiple properties if you want to support
programmatic construction in a single line of code.

Note that the JavaBean properties are not declared on the business interface
callers will work with. They're an implementation detail. We can easily "plug
in" different implementing classes that have different bean properties without
affecting connected objects or calling code.

Of course Spring XML bean factories have many more capabilities than described
here, but this should give you a feel for the basic approach. As well as
simple properties, and properties for which you have a JavaBeans
PropertyEditor, Spring can handle lists, maps and java.util.Properties. Other advanced
container capabilities include:


  • Inner beans, in which a property element contains an anonymous bean
    definition not visible at top-level scope

  • Post processors: special bean definitions that customize container
    behavior

  • Method Injection, a form of IoC in which the container implements an
    abstract method or overrides a concrete method to inject a dependency. This
    is a more rarely used form of Dependency Injection than Setter or
    Constructor Injection. However, it can be useful to avoid an explicit
    container dependency when looking up a new object instance for each
    invocation, or to allow configuration to vary over time--for example, with
    the method implementation being backed by a SQL query in one environment and
    a fil system read in another.
Bean factories and application contexts are often associated with a scope
defined by the J2EE server or web container, such as:


  • The Servlet context. In the Spring MVC framework, an application context is
    defined for each web application containing common objects. Spring provides
    the ability to instantiate such a context through a listener or servlet
    without dependence on the Spring MVC framework, so it can also be used in
    Struts, WebWork or other web frameworks.

  • A Servlet: Each controller servlet in the Spring MVC framework has its own
    application context, derived from the root (application-wide) application
    context. It's also easy to accomplish this with Struts or another MVC
    framework.

  • EJB: Spring provides convenience superclasses for EJB that simplify EJB
    authoring and provide a BeanFactory loaded from an XML document in the EJB
    Jar file.
These hooks provided by the J2EE specification generally avoid the need to use
a Singleton to bootstrap a bean factory.

However, it's trivial to instantiate a BeanFactory programmatically if we
wish. For example, we could create the bean factory and get a reference to the
business object defined above in the following three lines of code:

XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("myFile.xml", getClass()));
MyBusinessObject mbo = (MyBusinessObject) bf.getBean("exampleBusinessObject");
This code will work outside an application server: it doesn't even depend on
J2EE, as the Spring IoC container is pure Java. The Spring Rich project
(a framework for simplifying the development of Swing applications using
Spring) demonstrates how Spring can be used outside a J2EE environment, as do
Spring's integration testing features, discussed later in this article.
Dependency Injection and the related functionality is too general and valuable
to be confined to a J2EE, or server-side, environment.



A sneak peek at the Native Client SDK


Today, we’re happy to make available a developer preview of the Native Client SDK – an important first step in making Native Client more accessible as a tool for developing real web applications.


When we released the research version of Native Client a year ago, we offered a snapshot of our source tree that developers could download and tinker with, but the download was big and cumbersome to use. The Native Client SDK preview, in contrast, includes just the basics you need to get started writing an app in minutes: a GCC-based compiler for creating x86-32 or x86-64 binaries from C or C++ source code, ports of popular open source projects like zlib, Lua, and libjpeg, and a few samples that will help you get you started developing with the NPAPI Pepper Extensions. Taken together, the SDK lets you write C/C++ code that works seamlessly in Chromium and gives you access to powerful APIs to build your web app.



To get started with the SDK preview, grab a copy of the download at code.google.com/p/nativeclient-sdk. You’ll also need a recent build of Chromium started with the --enable-nacl command-line flag to test the samples and your apps. Because the SDK relies on NPAPI Pepper extensions that are currently only available in Chromium, the SDK won’t work with the Native Client browser plug-ins.

We’ll be updating the SDK rapidly in the next few months, so download a copy, develop some cool apps, share them with the community and send us your feedback! If you build useful libraries in the process, please also consider submitting a patch to the SDK packages directory – chances are, what’s been useful to you will be useful to others. Finally, if you’re attending Google I/O, come to our Beyond JavaScript session, or meet the team at the Developer Sandbox.

Welcome to this early preview of the Native Client SDK. With the SDK and a Windows, Mac OS X, or Linux computer, you'll be able to build web apps that seamlessly use native C/C++ code to perform high-performance computation, render 2D/3D graphics, play audio, and respond to mouse and keyboard events — all without requiring users to install a plugin. Until Native Client is on by default in Google Chrome, you can run web apps that use Native Client by launching Google Chrome version 6 or later with the --enable-nacl flag.

Note:
This SDK and the APIs that you can use with Native Client
will change.
Watch this page or the
discussion group
for news.

If you're interested in the implementation of Native Client, rather than using it to build apps, see the Native Client project.

How to start

How you should start working with Native Client depends on whether you want to try out the SDK in its current early stage. If you don't — if you just want to run a few apps that use Native Client — follow the instructions in How to Run Modules, or if you have are running a NaCl-enabled browser, visit our Gallery.
If you want to try out the SDK, here's what we recommend:
  1. Follow the "Getting Started" instructions

    You'll download the SDK and the Dev channel build of Google Chrome, you'll run sample apps, and you can modify and rebuild the apps.
  2. Subscribe to our discussion group
  3. Give us feedback
  4. Contribute to our design work
  5. For the intrepid, try out the lastest Pepper 2 experimental version. This is not for the faint-of-heart.
You can also watch our Google I/O 2010 talk:


Slides and more

Using open-source libraries

Many useful C and C++ libraries have already been ported to Native Client. For a list of ported open-source libraries, see the packages/scripts/ directory of the naclports project. Instructions for building these packages are in the README. If you'd like to port another library, see HowTo_PortCode.

More information

For information about Native Client, see:

High-performance Web development with Google Web Toolkit and Eclipse Galileo

Michael Galpin, Software architect, eBay
Summary:  By now, you have probably heard of Google Web Toolkit (GWT). You know
that it lets you write your Web applications in the Java™ programming language that is compiled into
JavaScript to run in Web browsers. This lets you be more productive by taking
advantage of Java's static typing and great tools like Eclipse. You have may
seen some of the useful and stylish widgets built on top of GWT. What
you may not know is that GWT lets you create high-performance Web
applications. In this article, we look at how you can use the Google
Plug-in with Eclipse Galileo to tap into the performance features of GWT, such
as compiler optimizations, deferred binding, and Ajax optimizations. Developer
performance is still an important part of GWT, so along the way, we will also
show you how tweak the Google Plug-in for Eclipse to increase your
productivity.

Prerequisites

In this article, we will take a look at several features of GWT and examine
how they enable you to build high-performance Web applications. This
article is not an introduction to GWT, so prior experience with GWT
is assumed. It is also assumed that
you know Java technology and that you are familiar with JavaScript, CSS, and HTML.
It is recommended that you use the latest version of GWT: V1.7 was
used for this article. This article also uses the Google Plug-in for
Eclipse. V1.1 of the Google Plug-in was used with Eclipse V3.5
(Galileo) for this article. We will also use the Firebug
plug-in for Mozilla Firefox. V1.4.2 of Firebug was used, along with
Firefox V3.5.2 (see Resources).


GWT is well known for its ability to compile Java into JavaScript,
enabling Java developers to develop dynamic Web applications. All the code
is compiled into JavaScript, and many of GWT's performance features were
designed to make JavaScript run faster in the browser. There are several
such features in GWT, including browser-specific optimizations and
streamlined Ajax, but most of the features start with GWT's Java-to-JavaScript compiler. So that is where we will begin our exploration of
GWT's performance-related features.

Compiler optimizations

The GWT compiler is what translates your Java code into JavaScript
that runs in the browser. However, it does much more than simply translate
Java technology into JavaScript. The compiler does numerous optimizations to make
your code run faster. However, it can be difficult to understand exactly
what is going on with these optimizations, as the JavaScript emitted by
GWT is obfuscated and very hard to read. First, we want to instruct the
GWT compiler to produce some human-readable JavaScript, so we can get a
better idea of exactly what optimizations the compiler is making.

The GWT compiler has three modes of operation. The default mode is
obfuscated, in that the GWT compiler will emit obfuscated JavaScript. This
JavaScript is not just difficult to read but it is compressed. This makes it
smaller, so it loads faster over the Internet. The smaller size also helps
the browser to parse the JavaScript quicker.

Some of you might be thinking
that sending compressed JavaScript over the wire makes little difference
since most Web servers send JavaScript using gzip compression, as gzip
compression is supported by any modern Web browser. However, not only does
the GWT compiler compress the JavaScript but it does so in a way that is
engineered with gzip compression in mind. In other words,
GWT-obfuscated JavaScript is highly gzip-compressible, despite being already
compressed. Thus, if your Web server is not using gzip, you will
obviously get a big speed boost by using GWT obfuscation. However, even if
your Web server is using gzip, you will still get a significant boost from
GWT obfuscation.

So for production code, we clearly want the GWT compiler set to emit
obfuscated JavaScript. However, this clearly makes it nearly impossible to
read the emitted JavaScript. To see this, take a look at some GWT-obfuscated JavaScript in Listing 1.


Listing 1. Obfuscated JavaScript
function qH(){return np}
function mH(){}
_=mH.prototype=new mu;_.gC=qH;_.tI=0;function
uH(){uH=ZH;sH={};tH=[];sH[LM]=[Is,Hs,Js];sH[JM]=[rt,qt,st];Xv(tH,yn,LM);Xv(tH,To,JM)}
var sH,tH;function AH(a){a.b=oH(new mH);return a}
function BH(a){var b,c,d,e,f,g,h,i,j,k;g=ox(new cx,MM);f=OA(new FA);j=XH(new
 VH,NM,OM);KA(f,j.b+sJ+j.c);pw(g.B,PM,true);Zw(gA(QM),f);Zw(gA(RM),g);f.B.focus()
;k=Jg(f.B,NJ).length;k>0&&JA(f,0,k);c=py(new my);Lf((tf(),c.b.B),SM);c.o=true;
b=ox(new cx,TM);b.B.id=UM;i=Py(new Ny);h=Ty(new My);d=UA(new RA);pw(d.B,VM,true);
VA(d,Uy(new My,WM));VA(d,i);VA(d,Uy(new My,XM));VA(d,h);d.b=(kz(),jz);VA(d,b);
Ax(c.j,d);Mx(c);vw(b,FH(new DH,c,g),(sh(),rh));e=KH(new IH,a,g,f,i,h,c,b);
vw(g,e,rh);vw(f,e,(hi(),gi))}
function CH(){return rp}
function xH(){}



Luckily, it is easy to coax the GWT compiler into creating some much more
human-eadable JavaScript. You can simply pass the compiler a
-style=PRETTY argument. This is made even
easier using the Google Plug-in for Eclipse. When you trigger a GWT
compile, it will bring up the dialog shown in Figure 1.



Figure 1. GWT compiler options

Screen shot showing GWT compiler options





To see the JavaScript that the compiler is emitting,
just choose the Pretty setting shown in Figure 1. Now the code will look
more like what is shown in Listing 2.


Listing 2. Pretty JavaScript
var $wnd = parent;
var $doc = $wnd.document;
var $moduleName, $moduleBase;
var $strongName = '21B409FCD39529C5A9DB925F7D8D9A95';
var $stats = $wnd.__gwtStatsEvent ? function(a) {return 
   $wnd.__gwtStatsEvent(a);} : null;
$stats && $stats({moduleName:'gwtperf',subSystem:'startup',evtGroup:
'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalStart'});
var _;
function nullMethod(){
}

function equals(other){
  return this === (other == null?null:other);
}

function getClass_0(){
  return Ljava_lang_Object_2_classLit;
}

function hashCode_0(){
  return this.$H || (this.$H = ++sNextHashId);
}

function toString_0(){
  return (this.typeMarker$ == nullMethod || this.typeId$ ==
2?this.getClass$():Lcom_google_gwt_core_client_JavaScriptObject_2_classLit)
.typeName + '@' + toPowerOfTwoString(this.typeMarker$ == nullMethod || this.typeId$
== 2?this.hashCode$():this.$H || (this.$H = ++sNextHashId), 4);
}

function Object_0(){
}

_ = Object_0.prototype = {};
_.equals$ = equals;
_.getClass$ = getClass_0;
_.hashCode$ = hashCode_0;
_.toString$ = toString_0;
_.toString = function(){
  return this.toString$();
}
;



This is still highly optimized JavaScript, but is much easier to
understand. Of course, this makes a big difference in the size of the
JavaScript being created. We can examine this by using the Firebug plug-in
for Firefox, as shown in Figure 2.



Figure 2. Comparing JavaScript file
size: Obfuscation vs. Pretty


Screen shot comparing JavaScript file size: Obfuscation vs. Pretty





Figure 2 shows the same GWT application (the starter project created by the
Google Plug-in) compiled with obfuscated JavaScript (at the top) and
compiled with pretty JavaScript (bottom.) As you can see from the figure,
the JavaScript size goes from 58 KB to 146 KB when going from obfuscated
to pretty.

Now we can take a look at some code to see how the GWT compiler optimizes
it. One of the ideas behind GWT is that you can write your code using
software engineering best practices. You can introduce the right kind of
abstractions that will make your code robust and maintainable. Meanwhile,
GWT will compile into very fast code. Let's take a sample trivial
class for modeling users, as shown in Listing 3.


Listing 3. A Person class
public class Person {
    final String firstName;
    final String lastName;
    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public String getName(){
        return firstName + " " + lastName;
    }
}



Now, we will alter the following code from the GWT start project, shown in
Listing 4.


Listing 4. Original GWT start project code
final TextBox nameField = new TextBox();
nameField.setText("GWT User");



Now we will simply use our Person object in
place of the hard-coded string shown above. This change is shown in
Listing 5.


Listing 5. Modified to use the Person
final TextBox nameField = new TextBox();
final Person user = new Person("GWT", "User");
nameField.setText(user.getName());



This is a simple change, but it is easy to imagine this being a useful
abstraction for an application. However, there could be a price to pay in
terms of performance. There is (potential) overhead in object creation and
in method dispatch. Let's take a look at how the GWT compiler can help
out. Listing 6 shows the compiled version of the original code.


Listing 6. Original code, compiled to JavaScript
nameField = $TextBox(new TextBox());
nameField.element['value'] = 'GWT User' != null?'GWT User':'';



Now let's take a look at what Listing 5 looks like when compiled to
JavaScript. This is shown in Listing 7.


Listing 7. Modified code, compiled to JavaScript
user = $Person(new Person(), 'GWT', 'User');
  $setText_1(nameField, user.firstName + ' ' + user.lastName);



The first line of code is calling the JavaScript constructor for the
Person class. This is a straight translation of
the Java code. The second line of code has been changed a bit. Instead of
calling the getName() method on the
Person instance, the method that has been inlined.
That is the call to the method has been replaced by the body of the
method. This is a common optimization done by compilers —
historically,
C/C++ and Java compilers — but is a trick that the GWT compiler takes
full advantage of as well to produce fast JavaScript.

It is common in object-oriented development to abstract out a common
interface that may have multiple implementations and write code that
works with the interface, making it more reusable. This is another
useful engineering abstraction that can impose extra lookups and method
dispatch, hurting performance. Let's take a look at how the GWT
compiler can help with that. You can use Eclipse's refactoring tools to
easily extract an interface from the Person
class in Listing 3. Let's call that a Thing. It is shown in Listing 8.


Listing 8. Refactored with Thing interface
public interface Thing {
    String getName();
}
public class Person implements Thing {
    final String firstName;
    final String lastName;
    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public String getName(){
        return firstName + " " + lastName;
    }
}



Now the client code that uses the Person should
be changed to use the Thing interface. This is
shown in Listing 9.


Listing 9. Refactored client code
Thing user = new Person("GWT", "User");
nameField.setText(user.getName());



What happens to the compiled code? Do we pay a performance price? Take
a look for yourself in Listing 10.


Listing 10. Refactored code, recompiled
user = $Person(new Person(), 'GWT', 'User');
$setText_1(nameField, user.firstName + ' ' + user.lastName);



As you can see, there are no changes at all. What if we have two
implementations of the interface that are both used? The code for this is
shown in Listing 11.


Listing 11. Multiple implementations of Thing
public class Company implements Thing {
    private final String name;
    public Company(String name){
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
}
// client code
final TextBox nameField = new TextBox();
Thing user = new Person("GWT", "User");
Thing userCompany = new Company("ACME");
nameField.setText(userCompany.getName() + " " + user.getName());



Listing 12 shows the JavaScript emitted by the GWT compiler.


Listing 12. Multiple implementations compiled away
user = $Person(new Person(), 'GWT', 'User');
userCompany = $Company(new Company(), 'ACME');
$setText_2(nameField, userCompany.name_0 + ' ' + (user.firstName + ' ' + user.lastName));
            



As you can see, the compiler still removes the interface and still inlines
each implementation of the getName() method.
This is still quite optimal code. However, there are things you can
do that can prevent optimizations, as shown in Listing 13.


Listing 13. Defeating the compiler
private String mkString(Collection<Thing> things, char separator){
    StringBuilder sb = new StringBuilder();
    for (Thing thing : things){
        sb.append(thing.getName());
        sb.append(separator);
    }
    return sb.deleteCharAt(sb.length()).toString();
}
// client code
final TextBox nameField = new TextBox();
Thing user = new Person("GWT", "User");
Thing userCompany = new Company("ACME");
nameField.setText(mkString(Arrays.asList(user, userCompany), ' '));



In Listing 13, we have introduced a new abstraction: a helper function for
taking a collection of Thing objects and
concatenating the result of calling getName()
on each Thing. The separator is also abstracted
out as a parameter to this function. Now let's look at the compiled
JavaScript in Listing 14.


Listing 14. Compiled mkString code
function $mkString(things, separator){
  var sb, thing, thing$iterator;
  sb = $StringBuilder(new StringBuilder());
  for (thing$iterator = $AbstractList$IteratorImpl(new AbstractList$IteratorImpl(), 
things); thing$iterator.i < thing$iterator.this$0.size_0();) {
    thing = dynamicCast($next_1(thing$iterator), 16);
    $append_2(sb, thing.getName());
    sb.impl.string += String.fromCharCode(separator);
  }
  return $deleteCharAt(sb, sb.impl.string.length).impl.string;
}
// client code
user = $Person(new Person(), 'GWT', 'User');
userCompany = $Company(new Company(), 'ACME');
$setText_1(nameField, $mkString($Arrays$ArrayList(new Arrays$ArrayList(), 
initValues(_3Lorg_developerworks_gwt_client_Thing_2_classLit, 0, 16, 
  [user, userCompany])), 32));



The code in Listing 14 is of similar complexity as the Java source code.
Notice that inside the loop, a function called
dynamicCast is called. This is JavaScript used
to check if the object passed to it can be cast to an object of a given
type. In this case, it will check if the object is a
Person or a Company,
as these are the only objects implementing
Thing. By introducing code written
against the interface and having multiple implementations of the
interface, there are fewer optimizations that can be done by the GWT
compiler.

So far, all of the optimizations that we have looked at were language-level
optimizations made by the GWT compiler. There are other more
browser-specific optimizations that can be done by GWT. These types of
optimizations are generally lumped under the umbrella concept known as
deferred binding.

Deferred binding

Web developers have been suffering from the variations across Web browsers
ever since Mosaic was no longer the only browser around. One of the great
appeals of the many JavaScript frameworks out there is to smooth over the
differences between browsers to make your life a little more
sane. There are two common approaches to this. First, you can write code
that is portable across browsers. This is a least-common denominator
approach, which is at best slightly less than optimal, but more often, it is
far from optimal. The other approach is to sniff the browser and use the
optimal code for each browser. This causes a lot of spaghetti code and
implies that there will be a lot of code shipped to the browser that is
never executed on the browser.

GWT's deferred binding architecture allows it to compile multiple versions
of JavaScript for the various browsers. A small piece of JavaScript is
downloaded to the browser to sniff the browser, then the optimized
JavaScript is downloaded. If you look back at Figure 2, you will notice a
.nocache.js file that was downloaded. This is the browser-sniffing code,
and in this case, was 4 KB. By default, four permutations are
checked: Opera, Safari, Gecko (Firefox V2 or less), Gecko V1.8 (Firefox
V3+), Internet Explorer V6, and Internet Explorer V8.

The classic example of an API that differs greatly across browsers is
setting the innerText property of an element.
This is done in the starter project in the callback handler to the remote
procedure call to the server. The Java code is quite simple and is shown
in Listing 15.


Listing 15. Setting text in GWT
public void onSuccess(String result) {
    dialogBox.setText("Remote Procedure Call");
    serverResponseLabel.removeStyleName("serverResponseLabelError");
    serverResponseLabel.setHTML(result);
    dialogBox.center();
    closeButton.setFocus(true);
}



Now let's take a look at what the GWT compiler will emit for various
browsers. To figure out what file is being compiled for each browser
permutation, take a peek into the .nocache.js file and look for a section
of code that looks similar to the code shown in Listing 16.


Listing 16. GWT's browser-sniffing code
if (!strongName) {
  try {
    unflattenKeylistIntoAnswers(['opera'], 
'D1B884746B9C511E12378A55F9FD97E2.cache.html');
    unflattenKeylistIntoAnswers(['safari'], 
'12DC532DA52018F17FA7F84F7137102A.cache.html');
    unflattenKeylistIntoAnswers(['gecko1_8'], 
'0986E60F243CC620FA7138AB06F221EB.cache.html');
    unflattenKeylistIntoAnswers(['gecko'], 
'CF1F7CBAF43D18B03F82260D99CB1803.cache.html');
    unflattenKeylistIntoAnswers(['ie8'], 
'1EE88964C0A866A7F2887C02F69F64D3.cache.html');
    unflattenKeylistIntoAnswers(['ie6'], 
'5395DF4A8135D37430AAE1347158CE76.cache.html');
    strongName = answers[computePropValue('user.agent')];
  }
  catch (e) {
    return;
  }
}



Now you can match up each of the keys ('opera', 'safari', etc.) to the
generated files. Using this, now we can find the version of the
onSuccess method from Listing 15 that was
compiled for Internet Explorer V6, shown in Listing 17.


Listing 17. Compiled for Internet Explorer V6
function $onSuccess(this$static, result){
  ($clinit_11() , this$static.val$dialogBox.caption.element)
.innerText = 'Remote Procedure Call';
  setStyleName(this$static.val$serverResponseLabel.element, 
'serverResponseLabelError', false);
  this$static.val$serverResponseLabel.element.innerHTML = result || '';
  $center(this$static.val$dialogBox);
  $setFocus(this$static.val$closeButton, true);
}



For Internet Explorer V6, GWT uses the optimal API for Internet Explorer
V6: using the innerText property
of the element. Now let's compare this to the Gecko V1.8+ permutation shown
in Listing 18.


Listing 18. Compiled for Firefox V3+
function $onSuccess(this$static, result){
  ($clinit_11() , this$static.val$dialogBox.caption.element)
.textContent = 'Remote Procedure Call';
  setStyleName(this$static.val$serverResponseLabel.element, 
'serverResponseLabelError', false);
  this$static.val$serverResponseLabel.element.innerHTML = result || '';
  $center(this$static.val$dialogBox);
  $setFocus(this$static.val$closeButton, true);
}



For newer versions of Firefox, GWT compiles the Java code into JavaScript
that uses the textContent property of the
element. This is a simple example, but you could easily imagine using
something like innerText multiple times in your
application code.

If you develop much with GWT, you quickly become aware of deferred binding
— but not always for the best reason. As we have seen, GWT compiles a
different version of JavaScript for each permutation of your application.
These permutations are also how GWT localizes your code. By default, there
are six browser variations and one language. If you needed to support
three languages instead of one, there would be 18 permutations and
18 versions of the JavaScript. This can often lead to long compiles
that can really cut into your productivity. Of course, one
way to overcome this is to do most of your work in Hosted Mode, where you
do not compile to JavaScript at all. This is by far the easiest way to
debug your code. However, if you need to compile, you can greatly
reduce the compile time by telling GWT to only compile for one browser
(whatever browser you like to use for testing.) All you have to do is
modify the module XML configuration file for your application, as shown in
Listing 19.


Listing 19. Configure GWT for one browser
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.0//EN" 
"http://google-web-toolkit.googlecode.com/svn/tags/1.7.0/distro-source/core
/src/gwt-module.dtd">
<module rename-to='gwtperf'>
  <!-- Inherit the core Web Toolkit stuff.                        -->
  <inherits name='com.google.gwt.user.User'/>

  <!-- Inherit the default GWT style sheet.  You can change       -->
  <!-- the theme of your GWT application by uncommenting          -->
  <!-- any one of the following lines.                            -->
  <inherits name='com.google.gwt.user.theme.standard.Standard'/>
  <!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
  <!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/>     -->

  <!-- Other module inherits                                      -->

  <!-- Specify the app entry point class.                         -->
  <entry-point class='org.developerworks.gwt.client.GwtPerf'/>
  <set-property name="user.agent" value="gecko1_8"/>
</module>



The key here is the next-to-last line: the
set-property tag. We simply set the
user.agent property to
gecko1_8 and now GWT will only do one compile
that produces JavaScript targeted for Firefox V3+. We have now seen some of
the many ways that GWT produces just the right JavaScript that will run
the fastest in the user's browser.

High-speed Ajax

Ajax has become ubiquitous on the Web, and it is an essential part of any
Web application. When the Ajax term was coined, the X in Ajax stood for
XML. This was assumed to be the format for data being sent between
browsers and servers. However, many Ajax applications actually receive
HTML from the servers that they communicate with. This is usually done
because it is the easiest thing to implement. It is far from optimal,
though.

Some Ajax application servers send back data in the form of XML. This is a
huge improvement over HTML, but it is also suboptimal. XML is a bulky
format and can be awkward to parse using JavaScript. This leads to too
many bytes being sent over the wire, and too much JavaScript has to be
executed that the user has to wait for. Many Web applications have
switched to using JSON. This is an improvement.

GWT includes both client-side and server-side components for Ajax, so
you might wonder what data format GWT uses for Ajax. It probably comes as
no surprise that GWT uses a unique format that is highly optimized. To
take a look at it, Firebug once again comes in handy, as shown in Figure
3.



Figure 3. Monitor Ajax traffic with
Firebug


Screen shot depicting monitoring Ajax traffic with Firebug





Firebug shows data sent to the server and the data returned by
the server. Take a more detailed look in Listing 20.


Listing 20. GWT request and response data
Request: 
5|0|6|http://localhost:8080/gwtperf/|29F4EA1240F157649C12466F01F46F60|
org.developerworks.gwt.client.GreetingService|greetServer|java.lang.String|
IBM developerWorks|1|2|3|4|1|5|6|
Response:
//OK[1,["Hello, IBM developerWorks!<br><br>I am running Google App Engine
Development/1.2.2.<br><br>It looks like you are using:<br>Mozilla/
5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/
3.5.2"],0,5]



Of course, the Java code you would write is quite simple. GWT provides a simple programming model at design time, but a highly
optimized runtime implementation.

Summary

This article has shown many of the performance optimizations GWT
provides for developers and how to take advantage of the Google Plug-in
for Eclipse Galileo. GWT makes it easy to write dynamic Web applications
that are also high-performance Web applications. This will continue to get
even better. The upcoming GWT V2.0 release includes several
new features, such as code-splitting and resource bundles, that go even
further toward improving the performance of Web applications created with
GWT. You can get early access to these features by building the GWT trunk
source code.

Download
DescriptionNameSizeDownload method
Source codeos-eclipse-googlegalileo-source.zip36KBHTTP
Information about download methods


Resources
Learn
Get products and technologies