Configure Tomcat 9 for HTTP/2

One of the most significant advancements in JavaEE 8 is support for HTTP/2. Three server vendors currently support servlet 4.0, Apache Tomcat 9.0.0.M4, Jetty 9 and WildFly 10.0.0.Final. Lets have a look at how to configure Tomcat 9 to support HTTP/2.

I often post about Servlet 4.0 on Twitter. Follow me here

Java EE Revisits Design Patterns

This and subsequent posts are a write up of my Java EE revisits design patterns talk at jDay Sweden 2016.

The slides to the presentation are viewable here: Java EE Revisits Design Patterns and a video of the presentation will be made available as soon as jDays publish it.

The book that accompanies this talk is available from Amazon.

qMaster Java EE design pattern implementation to improve your design skills and your application’s architecture

Professional Java EE Design Patterns is the perfect companion for anyone who wants to work more effectively with Java EE, and the only resource that covers both the theory and application of design patterns in solving real-world problems. The authors guide readers through both the fundamental and advanced features of Java EE 7, presenting patterns throughout, and demonstrating how they are used in day-to-day problem solving.

The talk has been divided up into the following sections.

Design patterns: the beginning

The beginning

Where did they come from? Did they just appear overnight? In fact design patterns have a long history starting way before computing. But it wasn’t really until the GOF wrote their seminal book Design Patterns: Elements of Reusable Object-Oriented Software, that the concept of design patterns was cemented in the world of software development. The book introduces a list of design patterns categorised under three titles: creational, behavioural and structural.

So what are design patterns in practice? Design patterns are solutions to problems already solved. They represent the collective wisdom of developers and provide us with a common vocabulary. By implementing solutions that are proven to work we avoid reinventing the wheel and can focus our efforts on solving the other problems we will face as we develop our application.

However, we need to take care not to overuse them. Unnecessary use of patterns tends to overcomplicate code making it hard to maintain and poor design pattern knowledge leads to the inappropriate implementation of patterns to problems that they were not designed to solve. It is very much the case that: If the only tool you have is a hammer, then you will see every problem as a nail.

The book’s authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.

Enterprise Java and design patterns

After the GoF published their book, there was a talk at Java One 2000 about prototyping patterns for the J2EE platform this talk became success and the speakers published the talk as a book. Core J2EE Patterns

The GoF book describes a range of patterns, not all common in Enterprise Java, but those that are common are baked into the APIs of the platform, so instead of having to implement them yourself the platform has them ready to use out of the box. This had already happened by Java EE 5.

Java EE Programming Model

The Java EE programming model has been simplified substantially since J2EE. Annotations have replaced the XML description files, convention over configuration has replaced the tedious manual configuration and dependency injection hides the creation and look up of resources.

Resources are created and injected at injection points marked by annotations such as @Inject. All you need is a POJO that meets all of the conditions of the managed beans specification JSR 299 and depending on the annotation used it will become an EJB, servlet, singleton or RESTful web service.

The object is injected by the container and is determine by type. However using an interface as a type can confuse the container if there is more than one concrete implementation. It doesn’t know which object to inject. This confusion can be resolved by the use of a qualifier annotation that marks the concrete implementation you want to implement. We will see how this annotation is used with @Produces in the implementation of the factory pattern. Beans or objects that you want to inject that do not conform to JSR299 use the @Produces annotation to make them injectable.

JSR 299 Managed bean specification

  • It is not a nonstatic inner class.
  • It is a concrete class or is annotated @Decorator.
  • It is not annotated with an EJB component-defining annotation or declared as an EJB bean class in ejb-jar.xml.
  • It has an appropriate constructor. That is, one of the following is the case:
  • The class has a constructor with no parameters.
  • The class declares a constructor annotated @Inject.

No special declaration, such as an annotation, is required to define a managed bean. To enable CDI you must have a beans.xml file in your project (under the META-INF or WEB-INF).

Singleton Pattern

OK let’s have a look at our first pattern.

The singleton pattern is one of the most well-known design patterns and is used extensively by frameworks such as Spring, pool mangers and loggers.

If you read the GoF book, it’s about having a single instance of an object in the JVM which is only ever instantiated once within the life-cycle of the application. Once created it is not normally destroyed until the application terminates. Why do you need this? The GoF motivation was that heavy weight objects, that you would not want to create because they are expensive to have around, are created by the singleton.

If you have read any further in the GoF book, implementing the singleton pattern is quite none trivial. You have to start with some pretty unnatural constructs like private constructors, double locking and the like and in the end you still didn’t get thread safety. You need to think about thread safety as it’s a single instance being shared across the JVM and across multiple threads.

Java EE offers an elegant and easy way to implement the singleton pattern.

Singleton Pattern in Code

@DependsOn("DatabaseConnectionBean")
@Startup
@Singleton
public class Logger {

    @PostConstruct
    void constructExpensiveObject() {
        // Expensive construction
    }

}

@Inject
Logger logger;

@Singleton

The creation of the singleton class is done by the container and the container knows to create only one instance because the class is annotated with the @Singleton stereotype annotation. By default this object is read locked. Access to it is serialized, so you don’t have to worry about thread safety at all. So if two threads attempt to access the instance they will be forced into serialized access.

The container creates an instance of the Logger class and will inject the same instance wherever it finds an injection point. Injection points are annotated @Inject.

@PostConstruct

Let’s get to the expensive construction part. Remember this was one of the principle motivators of the design pattern and why you would want to have the singleton in the first place. We do this by adding the @PostConstruct annotation to the method that constructs the object. This is invoked at application start up.

@Startup

By default the singleton bean is initialized lazily: it won’t be created until first use. Normally this is sufficient for most use case scenarios, however you may want the singleton bean to perform application start up tasks in which case you must annotate the bean with @Startup: something that is not elegantly available in the classical implementation of this pattern. The container must ensure that the bean is initialized before it delivers client requests.

@DependsOn

The instantiation of your bean may depend on the initialisation of other beans. We can specify the bean on which we depend.

Conclusions so far

Already we have seen how the Java EE implementation of the singleton pattern is markedly different to its classical implementation and requires substantially less code to achieve the same results. You have been given more control over when the bean is instantiated, either at application start up or on first use, and you can specify its dependency on other beans successful instantiation. These new features enhance the behaviour and performance of the singleton bean.

But we can go further.

Now let’s look at how Java EE gives you even greater control over the pattern’s behaviour.

@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class Logger {

    @AccessTimeout(value = 30, unit=TimeUnit.SECONDS)
    @Lock(LockType.WRITE)
    public void addMessage(String message) {}

    @Lock(LockType.READ)
    public String getMessage() {}
}

Remember that I mentioned that the singleton bean is thread-safe by default as concurrency is managed by the container. Well, Java EE offers two types of concurrency management: container managed and bean managed concurrency. By default the container manages the concurrency, removing the need to implement the usual concurrency solutions.

@ConcurrentManagement

However we are given the option to manage it ourselves by choosing bean managed concurrency. Add the annotation ConcurrencyManagementType.BEAN to the class definition.

We still need to be careful with method access as our bean is exposed to a concurrent environment. Two lock types control access to the beans business method: WRITE and READ.

@Lock

Methods annotated WRITE, lock to other beans while being invoked. Methods that affect change will be annotated this way. Methods annotated READ allow concurrent access.

In this code snippet, a call to the getMessage method will be forced to wait until the addMessage method completes. This may result in a ConcurrentAccessTimeoutException if the addMessage method does not complete within the specified timeout period.

@AccessTimeout

The timeout period can be configured with an annotation either at the class level or the method level.

The Good, the Bad and the Ugly

The Good

Java’s EE manner of implementing the Singleton pattern has reduced substantially the lines of boilerplate code required to achieve a tread-safe Singleton. Not only that but it adds features to our singleton that it allows to be instantiated on application start-up or on first invocation. We can make its existence depend on the successful construction of another bean.

By convention the singleton has container managed concurrency but we can take back control and manage it ourselves we can even specify an access time out value.

The Bad

Over use of singletons can cause problem with you application as can the over use of anything. Lazy loading will cause delays on first use while eager loading may cause memory problems. An instance might be created on start-up but never used or garbage collected using up memory resources.

The Ugly

The singleton pattern is often considered an anti-pattern and should be used for niche use-case scenarios. It would be smarter to use a stateless session bean.