Transient and final instance variables in Java

In Java, transient and final are two important keywords and it is legal to put them as modifier of instance variables.

But how does it behave when it comes to object serialization? Since it is transient, we can guess such variable are not serialized and therefore, when the object is deserialized, they are initialized to their default values, like for regular non final instance variable.

But in fact, it depends! See the code below:

public class Diplodocus implements Serializable {

	private final transient String s1 = "test";
	private final transient String s2;
	private final transient String s3 = new String("hello");
	private final transient String s4 = s1 + s1 + 1;
	private final transient int i1 = 7;
	private final transient int i2 = 7 * 3;
	private final transient int i3 = Integer.MIN_VALUE;
	private final transient int[] a1 = {1,2,3};

	public Diplodocus() {
		s2 = "s2";
	}

	public static void main(String[] args) {

		File f = new File("diplo");
		try {
			FileOutputStream fos = new FileOutputStream(f);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(new Diplodocus());
			oos.flush();
			oos.close();

			FileInputStream fis = new FileInputStream(f);
			ObjectInputStream ois = new ObjectInputStream(fis);
			Diplodocus diplo = (Diplodocus) ois.readObject();
			ois.close();
			System.out.println("s1 = "+diplo.s1);
			System.out.println("s2 = "+diplo.s2);
			System.out.println("s3 = "+diplo.s3);
			System.out.println("s4 = "+diplo.s4);
			System.out.println("i1 = "+diplo.i1);
			System.out.println("i2 = "+diplo.i2);
			System.out.println("i3 = "+diplo.i3);
			System.out.println("a1 = "+diplo.a1);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

What we expect here is that the instance variables after the deserialization will be equals to the default initialization values : null for objects like Strings and 0 for the integers.

But, in fact the code has the following output:

s1 = test
s2 = null
s3 = null
s4 = testtest1
i1 = 7
i2 = 21
i3 = -2147483648
a1 = null

What happened?

During deserialization, the constructor of the object is not called. This is a special object instantiation process handled by the JVM. For regular non-final transient instance variable, they are assigned with their default values.

But what happened for final variables? There is a little trick.

If the final variable is blank, meaning that it is first initialized in the object constructor(s) (like on line 13), the deserialization will put the default value. That is why s2 = null.

On the contrary, for a final variable explicitly initialized, the value is reaffected, but only if this initializations is done in a certain manner, in fact, only if the initialization is done with what the Java specification calls a compile-time constant expression (§15.28).

Constant expressions are the ones you are allowed to use in the case labels of a switch statement. A constant expression is an expression, which can be resolved at compile-time with no ambiguity: somehow, it gives the guarantee that the resulting value will never change during the execution.

In our case, these are considered constant expressions and that is why the values are reaffected to the final variables (even if they are transient).

  • literals (like a String on line 3, or an integer on line 7)
  • + operation between literals and reference to a constant final variables (like on line 6)
  • * operation between integers (like on line 8)
  • reference to constants (like on line 9)

There are other types of constant expressions (e.g. cast operation to a primitive or a String). I suggest you to have a look at the specifications for more details1.

However, object instantiations are not considered to be constant expressions and that is why these are assigned to the default values (like on lines 5 and 10).

Conclusion

Be careful when you use transient final instance variable! You may expect to get attributes initialized or not according to the context. And the worst part is that, since they are final you cannot modify them directly afterwards.

  1. or simply check this: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28 []

Origami and Egyptian triangles (the Haga theorem)

I think most of us have only been taught Euclidian geometry at school. A ruler and a compass, the solid axioms of the Elements, and here we go!…

But as you probably know, even if it is pretty good to describe quite a lot of things, the Euclidian geometry suffers from some limitations. The famous Greek examples are doubling the cube (or the delian problem), the angle trisection and squaring the circle. We had to wait for the 19th century to show these problems where impossible to solve with the Euclidian geometry (i.e. with a ruler and compass only).

That is why other people invented other types of geometry. Thus, I lately came across some Web articles about origami geometry and I was quite surprised how powerful it is: it is indeed possible to solve some of the impossible problems above with origamis1. It was quite a revolution in my mind ! And where I am the most impressed is that you can achieve a lot with very limited materials: paper and folding…

The thing I did not know is that it exists many publications and theorems about origamis, although this field of research gained most of its popularity in the 20th centry. In this post, I will just give you an example (and a demonstration) of a famous theorem one can find about origami : the Haga theorem.

I like this theorem because it is very easy to understand and shows how you can have interesting geometrical reasonning from origamis. The demonstration is also not very complicated: you do not need more than highschool student geometrical notions to understand it.

The Haga Theorem

The Haga theorem comes from Kazuo Haga, a Japanese retired professor of biology from the University of Tsukuba.

To see what this theorem is, you first need a square piece of paper2. I really encourage you to do it at home because it is very visual.

Fold this square in two. Here is what you get:

So, the next step is simply to fold the paper so that the corner C goes to the point S, the place where the paper was folded in half. You should end up with something like this::

That’s all! The Haga theorem simply says:

But actually, I prefer to rephrase it like this:

The triangles SAV, SBT and TDU are all Egyptian triangles.

What are Egyptian triangles? Maybe we need some explanations…

Egyptian triangles

You should be familiar with the famous Pythagorean theorem stating that in a right triangle, the square of the length of the hypothenuse (the longest side) is equal to the sum of the squares of the length of the two other sides.

You may also know that the converse of this statement is true: if you have a triangle so that the square of the longest side is equal to the sum of the squares of the other sides, then you have a right triangle.

If the theorem have the name of the famous Greek mathematician of Samos, it seems that more ancient civilizations already know this laws, e.g. the Egyptians.
They indeed used a quite powerful tool: a rope with 13 knots evenly distributed. With this rope, they were able to draw right triangle very easily.
Here is how it works:

You take the rope so that you create a triangle with the length 3, 4 and 5. This is a pythagorician triplet, because and that shows that the triangle is a right triangle. You can then used the rope to do draw right angles and build pyramids!

This is where we have our definition: an Egyptian triangle is a right triangle which is similar to this rope-made triangle. Similar means that one triangle has the same shape but maybe with a different scaling. For example, the right triangle with the sides of length 6, 8 and 10 is an Egyptian triangle (because the length are the double of the rope triangle).

Go back to the origami

Let’s go back to the Haga theorem, we say we have SAV, SBT and TDU as Egyptian triangles, which means that they are all similar to the (3,4,5) triangle made of rope.

First, we demonstrate that these triangles are similar. We demonstrate this by showing that they all have the same angles. It is a property of similar shapes to have the same angles.
Since the sum of the angles in a triangle is always equal to 180° (or if you prefer). We can show with no difficulties that the angles of the triangles ASV and SBT are the same (as show on the figure).
Concerning angles and they are the same because they are vertically opposite. We can therefore conclude to the similarity between triangles SBT and TDU (and therefore SAV).

Let’s show now that the triangle SAV is Egyptian. For that we will assume the length of the side of the initial square piece of paper is 8. That means the length of AS is 4.

We will now try to find the value of AV.

We have
And Pythagoras says:
Then:

So we have , , and . Hey, that’s an Egyptian triangle!
And since SAV is similar to SBT and TDU, we have show that all these triangles are Egyptian! Q.E.D.

(Origami crane photography author: Andreas Bauer (Origami-Kunst)

  1. at least doubling the cube and the angle trisection problems []
  2. I let you figure out how you can get a square from a A4 piece of paper []

Java EE startup and shutdown callbacks

Hurray, this is the first post of this blog!
As a first subject, I would like to discuss a problem where it was quite hard to find a solution on the Web. Let me share this with you.

The problem

Given a standard Java EE 5 application (with EJBs, Servlets…), how to develop some code which will be started when the application startup/shutdown?

In other words, how to execute something when you start or stop your application?
Indeed, when you start the server you may need to initialize some stuff like initializing your cache, and when you stop the server, wouldn’t it be great to do some data cleanup?

In my case, our application was a pure back-end application (only EJBs) which embedded a remote service interface and we wanted to register it (resp. unregister it) to a service locator at the application startup (resp. shutdown).

Unsatisfactory solutions

Application server and framework tricks

In fact, most of the application servers already come with their own solutions. In Weblogic, for example, we have the notion of startup/shutdown classes (but admittedly, I have not tested it).

But in our case, we had to deploy on a JBoss 6 server! And moreover, wouldn’t it be preferable to have a pure Java EE way, so that it could be deployed anywhere with minimal configuration?

If we were using some Java development framework like Seam, there are also some tricks, like using an observer on the org.jboss.seam.postInitializatio event like this:

@Name("initializer")
public class Initializer {

   @Observer("org.jboss.seam.postInitialization")
   public void init() {
      // startup code here
   }
}

But once again, this is a specific solution and if you are not using Seam then you should find something else (besides, I haven’t looked for the implementation of the shutdown callback with Seam).

Static blocks in EJBs

So what if we just put static block in EJBs and let’s just hope that when the EJB class will be loaded, the static code will be executed?
Well, this is a bad idea. By definition, you have no control on how the EJBs are loaded by the application server. It may even not be called before the first invocation of the EJB.
So this is obviously not a good solution.

EJB 3.1

It is true that we are speaking only about Java EE 5 in this post, but I just want to mention that in Java EE 6 with EJB 3.1, we can use the pretty code below:

@Singleton
@Startup
public class StartupShutdownBean {

	@PostConstruct
	private void startup() {
		// your startup code here
	}

	@PreDestroy
	private void shutdown() {
		// your shutdown code here
	}

}

The solutions

So, the only solution found was to use the servlet API. But the good news is that you have two choices:

Using Servlet init and destroy methods

The idea here is to have the startup and shutdown code in the init() and destroy() methods of a servlet embedded in your application. So if you do not have any servlet in your application, you will have to create one like this with these methods.

public class InitServlet extends HttpServlet {

	@Override
	public void init() throws ServletException {
		// startup code here
	}

	@Override
	public void destroy() {
		// shutdown code here
	}
}

You should guarantee that this servlet is loaded on start-up, (and potentially before the other servlets). This is guaranteed by the following statement in the web.xml.

<servlet>
        <servlet-name>Init</servlet-name>
        <servlet-class>com.clempinch.InitServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
</servlet>

The number between the load-on-startup tag indicates the order in which servlet are loaded on startup (the lowest are first).
This solution is ok admittedly, especially if you have already servlets in your application. But what if you have none? Isn’t it a bit costly to create a servlet listening to coming requests just for two methods to call during the application life?
For that reason, I prefer therefore the second solution, which is…

Using Servlet context listeners (the one I prefer)

The other solution is still in the servlet API, and it is to use a servlet context listener.
This comes as a Java interface ServletContextListener. Classes implementing this interface will be loaded before (resp. after) the instantiation (resp. the destruction) of all servlets, therefore, it is a good place to put your application startup/shutdown code.
Here is how it is done:

public class InitContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent ce) {
        // startup code here
    }

    @Override
    public void contextDestroyed(ServletContextEvent ce) {
        // shutdown code here
    }
}

You will also need to declare the context listener in the web.xml with the following statement:

<listener>
	<listener-class>com.clempinch.InitContextListener</listener-class>
</listener>

That’s all…

Conclusion

So, to sum up, it seems that to have some startup/shutdown code in your application there is no other clean solution than to use the servlet API, either with the init()/destroy() methods or with a servlet context listener.

The other best/long-term/cleanest solution is of course to migrate to Java EE 6, but not everyone is ready to do it, right?