Threads in GWT?

Threads in GWT?

While it is widely reported that Google Web Toolkit does not support Java Threads and multi-threading, a number of aspects of concurrent applications can be emulated in GWT's single thread JavaScript world.

The particular features that are relatively easy to emulate are:

  • Timers
  • Background Execution
  • Locks
  • 'Thread-safe' Collections

An important theme in my implementation of onedb was to write code in Java, which can be used both in a JVM environment and a GWT/JavaScript environment. Unfortunately, even though the Java Concurrency API and GWT's concurrency features often provide similar features, their APIs are incompatible.

For instance, a codebase, which uses a java.util.Timer, cannot use a com.google.gwt.user.client.Timer at the same time.

This motivated me to write a simple abstract API (oneUtils), into which implementations for either a JVM environment or a GWT environment can be injected. Code, which uses this abstract API, can therewith be shared between JVM and GWT apps.

The abstract API currently supports the following features:


public interface Concurrency {

    public abstract TimerFactory newTimer();

    public abstract ExecutorFactory newExecutor();

    public abstract void runLater(Runnable runnable);

    public abstract OneLock newLock();

    public abstract CollectionFactory newCollection();

}

An implementation for JVM environments is included in the library (JreConcurrency), an implementation for a GWT environment is provided in the following gist:

Gist: Default Implementation of Concurrency API in GWT

Below a few usage examples for the API:

Usage of Executor API Usage of Timer API Usage of Thread-Safe Collections API

Please feel free to use the API + implementations. You can either grab the project from github or link to the project via Maven:

Dependency:


<dependency>
    <groupId>one.utils</groupId>
    <artifactId>oneUtils</artifactId>
    <version>0.0.3</version>
</dependency>

Repository:


<repositories>
    <repository>
        <id>onedb Releases</id>
        <url>http://dl.dropbox.com/u/957046/onedb/mvn-releases</url>
    </repository>
</repositories>