quinta-feira, 16 de janeiro de 2014

Caveat: javax.xml.ws.Service.create method is not thread safe!

Technology credits:

I've recently stumbled on some random exceptions in my Tomcat client-side Java code. Exceptions such as:

So after several hours of debug, i've managed to confine the problem to this single instruction:

Service.create(...);

This is an example of a 'Factory Method Pattern' gone horribly wrong. Why? Because 'by default' you can run multiple threads simultaneously in the same method. As this is a 'static' method this means that all threads invoke the same method at the same time. This results in random exceptions depending on the phase were the racing problem occurs.

To avoid this kind of problem in you own code, always remeber: Constructors are ALWAYS thread safe. If you cannot avoid the 'Factory Method Pattern' make sure you mark that and all other 'Factory Methods' in the same class as 'synchronized' which will slow down the creation of objects but will guarantee that no racing conditions occur.