About

Jadira is the home for Sousan and Chris Pheby's open source projects. These are reusable open source Java modules that provide first class solutions using the most effective current JEE technologies.

Search
Tag Cloud
...
Login
« Jadira Usertype 1.9 and 2.0 | Main | User Type Presentation »
Tuesday
Oct192010

The Worst Kind of Defect #1

One of the most dangerous categories of defect is the misuse of member variables in singletons.

For example

public class DefaultFooService implements FooService {

    private TheResult theResult;

    public TheResult handleServiceRequest(TheRequest request) {
        theResult = doStuff();
        doMoreStuff();
        return theResult;
    }
}

This code is dangerous, and needs urgent refactor. A safer form looks something like:

public class DefaultFooService implements FooService {

    public TheResult handleServiceRequest(TheRequest request) {
        TheResult theResult = doStuff();
        doMoreStuff(theResult);
        return theResult;
    }
}

In the first example, data can be bled from one thread to another. In a web application this can result in data bleeding from one user to another. In a business policy this can result in the wrong rules being applied. In a financial calculation this can result in the wrong answer.

This defect is serious, and not only because of its severity. It is also hard to find. Only concurrent tests have any opportunity of surfacing the problem. Getting good coverage of such tests is difficult and there is no guarantee you will spot the issue. Often code review, and experience are the only ways to find and prevent this issue. Findbugs, PMD and the like cannot detect these errors (although they can warn about misuse of static fields.

As application architectures move more and more to stateless service architectures, these kinds of problems are going to become more and more prevalent.

Where a singleton service must hold state, the only workable solution in Java, is the use of a ThreadLocal, for example:

public class DefaultFooService implements FooService {

    private ThreadLocal<TheResult> = new ThreadLocal<TheResult>();

    public TheResult handleServiceRequest(TheRequest request) {
        theResult.set(doStuff());
        doMoreStuff(theResult.get());
        return theResult.get();
    }
}

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>