![]() |
I've recently stumbled on some random exceptions in my Tomcat client-side Java code. Exceptions such as:
1 2 | javax.xml.stream.XMLStreamException: ParseError at [row,col]:[ 1 , 2 ] Message: The markup in the document preceding the root element must be well-formed. |
1 2 | javax.xml.stream.XMLStreamException: ParseError at [row,col]:[ 1 , 1 ] Message: Premature end of file. |
1 | javax.xml.stream.XMLStreamException: ParseError at [row,col]:[ 1 , 1 ] Message: Content is not allowed in prolog. |
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.