Top 10+1 professional “deal breakers” of 2013

This little list is my favorite top 10 (and one extra). I did hear some of them personally, some were told by my friends.
Without any kind of further comments, let’s see the list itself:

  1. Starting with this release, we do not have bugs. At all.
  2. Eeeh, unit testing is not for me.
  3. We want to be agile, but not so strict agile. We only want the cool stuff like standups, but not retros. Retros are bullshit anyway.
  4. – “I need a bit of help”. -“No, you don’t”.
  5. I don’t think our way of working should be adjusted at all.
  6. Unit tests will make your code less flexible.
  7. I understand it can be useful, but don’t write clean code; you’ll confuse everyone with so many classes and methods.
  8. Don’t do refactoring, it only breaks working code.
  9. Don’t write unit tests, nobody’s paying for those. Customers are paying for features.
  10. We will implement an automated test system sometime, but first we have to conduct a feasibility study.

And get ready for my favorite one:

+1.  Hudson’s been broken for the past few weeks. Somebody should take care of it.

JavaEE dependency injection – common mistakes

In this post, I will cover some common mistakes people make when it comes about injection in enterprise environment.

1.) @EJB and the new keyword

I’ve seen dozens of forum posts, was asked the question so many times: “Instead of injecting my dependencies, the container throws a NullPointerException. Why?”

Most of the times, the answer to this question is really simple: because you are instantiating your EJB with the new operator, and don’t let the container do its job. For example, let’s consider the following piece of code:

@Stateless
public class Car {

  @EJB
  private Engine engine;

  //...

  public void startEngine() {
    engine.start();
  }

  //...
}

@Stateless
public class CarSalon {

  //...

  public void testDrive() {
    Car car = new Car();
    car.startEngine();
    // ...
  }
}

You see both classes here are stateless session beans; however, if you tried to run the code above, you’d get a big fat NullPointerException. The reason is that the object Car is not managed by the container, even if it’s a session bean. When you use the new keyword, you get in charge for managing that object. An object instantiated this way is outside the reach of the container, and it has no way of injecting dependencies. None of the @EJB, @Resource, @PersistenceContext etc. injections will have any effect. Simply put, using new you can only create POJOs, not Enterprise Java Beans.

In order to fix this error, you have to get the container take care of the Car object. Nothing easier than that, we just have to either look up the bean tgrough an instance of the InitialContext class:

@Stateless
public class CarSalon {

  //...

  public void testDrive() {
    InitialContext context;
    try {
		context = new InitialContext();
		Car car = (Car)context.lookup(CAR_JNDI_NAME);
		car.startEngine();
		//...
    } catch (NamingException e) {
        //...
    }
}

or, have the container inject the dependency:

@Stateless
public class CarSalon {

  @EJB
  private Car car;
  //...

  public void testDrive() {
    car.startEngine();
    //...
  }
}

Either way, the container will get you a fully initialized instance of the bean from the bean pool. And all the injections start working again.

2.) POJO injection

By POJO injection, we can mean two different things: injecting POJOs into Beans, or injecting Beans into POJOs.

Unless we are using CDI (which may be the topic of another post), we cannot inject a POJO into a session bean. You can only inject EJBs into EJBs. Intuitively, you cannot use the @EJB annotation to inject a POJO (as it is not an EJB), also, you can only look up EJBs using the InitialContext (as POJOs have no JNDI names). In one sentence, without CDI you cannot inject POJOs anywhere.

The other way around, is possible, though. You can use a fully initialized EJB in your POJO code. The @EJB annotation will not work, as only an EJB can be injected into another EJB using annotations. However, your object needs not be an EJB to be able to use the InitialContext.lookup() mechanism (provided that there actually is a container running under your application).

Note that starting from EJB 3.1, JNDI names are standardized. If (using the example above) we suppose that we have an EAR called Salon_EAR amd an EJB project, called Salon_EJB then the JNDI name for the object Car is:  java:global/Salon_EAR/Salon_EJB/Car.

3.) EJB injection and constructors

This one is related to Glassfish(3.1.1) application server and perhaps several others (some other app servers may support this, but Glassfish is the reference implementation, so…)

Let’s get back to the car salon example above. Given this piece of code:

@Stateless
public class CarSalon {

  @EJB
  Car car;

  public CarSalon() {
    car.startEngine();
  }

  // ...
}

Surprisingly enough, this code will throw a NullPointerException in deploy time. The Car object injected using the @EJB annotation is not available in the constructor. And no, it’s not because CarSalon is created first and Car second (you can even annotate the Car class with @Startup to be sure about the initialization sequence).

What is the solution then? Is there no way of using container managed objects in the object initialization process? There is, fo course. Let’s move all the logic from the constructor into a @PostConstruct method. The code now looks like this:

@Stateless
public class CarSalon {

  @EJB
  Car car;

  public CarSalon() {
    System.out.println("Constructor");
  }

  @PostConstruct
  public void init() {
    System.out.println("PostConstruct");
    car.startEngine();
  }

  // ...
}

And guess what, this actually gets deployed. The post construct block will run as part of the initialization process, but still outside the constructor. It even makes your code cleaner since we all know that it is not a good idea to place work in the constructor. Not to say that all the injected resources are available in such methods.

Ups and downs of CountDownLatches – an example

CountDownLatches are an elegant means of synchronizing threads. However, I’ve rarely seen them in actual use in production software. Well, this may be related to two simple reasons:

  1. They are less known
  2. They might require extra care than usual lock objects

First things first. What’s a CountDownLatch? Well, it is a not very tricky construct for -as mentioned earlier- coordinating threads. You will observe when creating such an object, that a CountDownLatch takes one single construnctor argument: the count (of type int. More on this in a second). The construct itself has three important methods:

  • countDown(); Each call to this method will decrease the value of the count, exactly by one
  • await(); blocks the thread as long as the count is greater than zero. As soon as the count is down to zero, the blocked thread will be given a chance to run again.
  • await(timeOut, timeUnit); well, it’s pretty self-explanatory. It does the exact same thing as the one above, only with a configurable timeout.

It is easy to see that CountDownLatches are best when we know ahead how many threads we are coordinating. A quick example on this situation (sorry for the following physics stuff, I couldn’t come up with any better or fancier): It is known that the magnetic field around a wire is given by the formula: wire.
Let’s suppose we are given the radius (r), but have to calculate the exact value for magnetic permeability(u0) and current(I). Let’s also suppose those are calculated by separate threads, and we can calculate the value for the magnetic field(B) as soon as we have those values. In this case, it is obvious that exactly two pieces of data have to become available before we can start calculating, so it should be easy to use CountDownLatches. We can come up with a solution like the one below, in no time:

	private final CountDownLatch calculationLatch = new CountDownLatch(2);

	public MagneticFieldCalculatorWithLatch(double radius) {
		this.radius = radius;
	}

	public void setPermeability(double permeability) {
		this.permeability = permeability;
		calculationLatch.countDown();
	}

	public void setCurrent(double current) {
		this.current = current;
		calculationLatch.countDown();
	}

	public void calculateMagneticField() throws InterruptedException {
		calculationLatch.await();

		double field = (permeability * current) / 2 * Math.PI * radius;
		System.out.println("The magnetic field around the wire is: " + field);
	}

It’s pretty nice, huh?  I particularly like that I don’t have to include the keyword synchronized in all the signatures (just try making those methods synchronized, you will instantaneously cause a deadlock), there isn’t a boilerplate loop to check whether the data is available etc. Simply cool.

With a classical solution, we would have something like:

	public MagneticFieldCalculatorWithNotifications(double radius) {
		this.radius = radius;
	}

	public synchronized void setPermeability(double permeability) {
		this.permeability = permeability;
		notifyAll();
	}

	public synchronized void setCurrent(double current) {
		this.current = current;
		notifyAll();
	}

	public synchronized void calculateMagneticField() throws InterruptedException {

		while (!dataAvailable()) {
			wait();
		}
		double field = (permeability * current) / 2 * Math.PI * radius;
		System.out.println("The magnetic field around the wire is: " + field);
	}

	private synchronized boolean dataAvailable() {
		return permeability != null && current != null;
	}

Which seems (probably because I’m biased, as this is a post on latches) more tedious.

However, this second solution has a clear advantage compared to the first one (and this is why i put earlier that latches “require extra care”), namely that is more robust. Should you call setCurrent(…) in the first example twice, the calculation is corruptedThat is because upon the first call, the value of the current is set, and the count is decremented to one – just as expected. When you call the method for the second time, though, the value of the current gets overwritten and the latch’s count gets decremented again, reaching the value of zero. At that point the thread waiting because of the await() method call is woken up, however, the calculator has the value for the current only, and not for u0 (which is initialized to 0 by the JVM). Easy to spot that the calculation will be resulting in the magnetic field being equal to 0.

The second solution, however, will not exhibit this weakness, as the while loop guards against such usage errors.  That while loop will always put the thread back to the waiting state, unless we have all the required data available. The worst that can happen in the second case (provided that you call setCurrent twice and setPermeabiliy zero times) is an infinite loop, which is easier to notice, after all (in a large system, at least).

In conclusion, use CountDownLatches for elegant solutions, but use them with care. And of course, don’t rely on them excessively, use them in apropiate situations only.