J and I and Me
Dangerous Code Example in EJB 3.1 Spec
I am currently working on a training concerning Java EE Best
Practices. For that reason I am reading through quite some material
about Java EE and EJB. However, looking at the EJB 3.1 spec I realized
that the code examples are an example of rather bad coding practice.
As an example here is the original code from EJB 3.1 Spec p. 348. It is supposed to
show how
UserTransactions can be used:
@Stateless
@TransactionManagement(BEAN)
public class MySessionBean implements MySession {
@Resource
javax.transaction.UserTransaction ut;
@Resource
javax.sql.DataSource database1;
@Resource
javax.sql.DataSource database2;
public void someMethod(...) {
java.sql.Connection con1;
java.sql.Connection con2;
java.sql.Statement stmt1;
java.sql.Statement stmt2;
// obtain con1 object and set it up for transactions
con1 = database1.getConnection();
stmt1 = con1.createStatement();
// obtain con2 object and set it up for transactions
con2 = database2.getConnection();
stmt2 = con2.createStatement();
//
// Now do a transaction that involves con1 and con2.
//
// start the transaction
ut.begin();
// Do some updates to both con1 and con2. The container
// automatically enlists con1 and con2 with the transaction. stmt1.executeQuery(...);
stmt1.executeUpdate(...);
stmt2.executeQuery(...);
stmt2.executeUpdate(...);
stmt1.executeUpdate(...);
stmt2.executeUpdate(...);
// commit the transaction
ut.commit();
// release connections
stmt1.close();
stmt2.close();
con1.close();
con2.close();
}
... }
What is wrong with this code? Well, first of all it does not
compile. Quite honestly I wouldn't really care too much about that - an
example is fine as long as the important point is still brought
across. But in this case it does matter as we will see later on. So here is
what the method should read like:
public void someMethod() throws SQLException, NotSupportedException,
SystemException, SecurityException, IllegalStateException,
RollbackException, HeuristicMixedException,
HeuristicRollbackException {
In the original example any code concerning Exceptions
has been left out. So what happens if an
Exceptions is thrown? No
close() is ever called and therefore none of the resources are ever cleaned up. Let's fix this:
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class MySessionBean {
@Resource
javax.transaction.UserTransaction ut;
@Resource
javax.sql.DataSource database1;
@Resource
javax.sql.DataSource database2;
public void someMethod() throws SQLException, NotSupportedException,
SystemException, SecurityException, IllegalStateException,
RollbackException, HeuristicMixedException,
HeuristicRollbackException {
java.sql.Connection con1 = null;
java.sql.Connection con2 = null;
java.sql.Statement stmt1 = null;
java.sql.Statement stmt2 = null;
try {
con1 = database1.getConnection();
stmt1 = con1.createStatement();
con2 = database2.getConnection();
stmt2 = con2.createStatement();
ut.begin();
stmt1.executeUpdate("");
stmt2.executeQuery("");
stmt2.executeUpdate("");
stmt1.executeUpdate("");
stmt2.executeUpdate("");
ut.commit();
} finally {
if (stmt2 != null)
try {
stmt2.close();
} catch (SQLException ex) {
}
if (con2 != null)
try {
con2.close();
} catch (SQLException ex) {
}
if (stmt1 != null)
try {
stmt1.close();
} catch (SQLException ex) {
}
if (con1 != null)
try {
con1.close();
} catch (SQLException ex) {
}
}
}
}
This is the infamous try-catch-finally-try-catch block. The
null
checks actually avoid calling
close() on objects that have not been
created - as the creation might already have failed and and exception might have been thrown. As the
close() operation might throw an exception this also needs to be handled. IMHO it is OK to swallow the exception - there is not really anything that can be done as the resources are already being closed. Using Spring's
JdbcTemplate would have avoided the problem as the resource handling
is done by the template then. I would strongly recommend it in code like this. It can be used independently from the other parts of Spring - e.g. Dependency Injection can still be done by Java EE. See
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/jdbc.html#jdbc-core for details.
Now there is another thing that is still not OK - actually the most
important point. The
UserTransaction is never committed nor rolled back
if an exception occurs. Let's fix this, too:
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class MySessionBean {
@Resource
javax.transaction.UserTransaction ut;
@Resource
javax.sql.DataSource database1;
@Resource
javax.sql.DataSource database2;
public void someMethod() throws Exception {
java.sql.Connection con1 = null;
java.sql.Connection con2 = null;
java.sql.Statement stmt1 = null;
java.sql.Statement stmt2 = null;
try {
con1 = database1.getConnection();
stmt1 = con1.createStatement();
con2 = database2.getConnection();
stmt2 = con2.createStatement();
ut.begin();
stmt1.executeUpdate("");
stmt2.executeQuery("");
stmt2.executeUpdate("");
stmt1.executeUpdate("");
stmt2.executeUpdate("");
} catch (Exception ex) {
ut.setRollbackOnly();
throw ex;
} finally {
ut.commit();
if (stmt2 != null)
try {
stmt2.close();
} catch (SQLException ex) {
}
if (con2 != null)
try {
con2.close();
} catch (SQLException ex) {
}
if (stmt1 != null)
try {
stmt1.close();
} catch (SQLException ex) {
}
if (con1 != null)
try {
con1.close();
} catch (SQLException ex) {
}
}
}
}
So when a problem occurs the transaction will now be marked as
rollback only and ultimately rolled back. If there is no exception it will be
committed.
I hope I made no further mistakes in the code - let me know
otherwise. In Spring resource handling is done for you by the
Templates and therefore I might be doing something wrong here. Using
that approach would also have made the code a lot less complex.
So why this blog post? Bad resource handling and transaction
handling is far too common. I have done a lot of reviews and usually
Enterprise Java applications fail to do a good job in this
regard. This is dangerous, because
- The whole point of transactions
is to provide safety if something goes wrong. If you do not commit nor
roll back the transaction it will be left in an undefined state and all kinds of things might happen. This is
compromising the safety of transactions. So the transactions become
more or less
useless. You might as well just not use them at all.
- Not closing connections and statements will eventually lead to
resource leaks e.g. connection pools running out of connections. This
will at one point make the system fail.
- These problems are hard to detect - they will only surface if
exceptions are thrown. So finding and eliminating the problem is
complex. You should rather get it right from the start.
Sadly the EJB spec seem to do resource handling constantly wrong. The EJB spec is
not the only document that does resource and transaction handling
wrong. Quite the contrary: I have a read a lot of tutorial and other
documents that get this entirely wrong. However, IMHO at least the
example in the spec for using the
UserTransaction should show how to
use it in a bullet proof manner. This document is read by many
developers and other authors. Bad practices in such a document might
end up in a lot of code and other publications.
Random Thought about Google Dart
Here are some thoughts about Google Dart and its possible usages. They are just wild ideas, I have no information whether they will actually be implemented or whether they are shared by anyone at Google:
- Compiling Dart into JavaScript is a good idea. It means Dart is immediately usable on any platform. There is no other way to quickly get it out to so many developers. Users are not quickly to switch to new browser - think about IE6.
- I originally expected that a Plug In and VM for Dart on Chrome would be released quickly. Now I think that would have been a bad idea. Chrome would have had a good support for Dart while the rest of the browsers would have been left in the cold. They would probably not use the Google VM - remember that they also have their own JavaScript VMs. It is also unlikely that they would create their own Dart VM. So the current approach create a level playing field and makes it more likely for Dart to succeed.
- I think the Dart VM might be an option for Android - maybe not in the near term but probably in the long run. Also it might be enough for Google to have an alternative VM. It just means it has a stronger position if a deal with Oracle must be closed.
- Dart is a good fit for Google App Engine (GAE). Isolates have just one thread - that is also what Google App Engine enforces. That has the advantage that GAE can restart isolates. Isolates can be snapshotted and migrated to other VMs - which is great if you want to react to different load by offloading work from a machine. Isolates can only communicate via ports - that allows you to minimize dependencies to the outside. Again that is great if you want to restart or migrate Isolates. It might also be a way around the limitation that GAE won't allow you to open sockets. Java without Multithreading and without the possibility to open sockets is hard and no fun - and that is why I believe Java on GAE ist not that great. This changes dramatically if you use Dart.
So we will see where this is headed. Remember the first days of Java: It was seemingly all about Applets. Now it is all about the server. Technologies might succeed in other areas than originally planned.
If you are new to Dart - here is a presentation about Dart:
Labels: Dart, Google Dart
Spring and Scala
Scala is an interesting language that appeals to a lot of Java developers as it is statically typed - just like Java. However, Scala focuses on concurrent processing. The choice of frameworks for typically bread and butter issues that you see in Enterprise applications is rather limited. For that reason it makes sense to look at Spring as a very mature and established Java Enterprise technology and whether it can be used with Scala. So here is a presentation and some sample code:
https://github.com/ewolff/scala-springLabels: Scala, Spring
adesso Now On slideshare
My employer adesso AG is now on slideshare:
http://www.slideshare.net/adessoAG/ .
Most of the presentations are in German. There are quite a few already and of course there are more to come. I thought I would show three presentations here on the blog.
The most popular so far is about security and JSF (German):
Then there is this one about memory and performance analysis in Java - something I think every Java developer should understand (German) :
And this one about Requirements Engineering (German) :
PS: Of course there is still my personal slideshare account with English presentations at
http://www.slideshare.net/ewolff/Labels: Adesso, slideshare
Cloud PowerWorkshop at WJAX
This year at WJAX me and my colleagues Halil-Cem Gürsoy, Andreas Hartmann and Stephan Müller from adesso will present the Cloud Power Workshop for the first time. It will cover everything you need to know to implement application with Java for the Cloud.
We will cover
Google App Engine (GAE). It pioneered the PaaS Cloud approach and is quite broadly used nowadays. At the same time GAE has some limitations that you need to know about to successfully build application on the platform - in particular if you use Java.
Then
Cloud Foundry will be shown - it provides a very interesting approach to PaaS - because it supports relational databases and Tomcat which is quite a familiar platform for most Java developers.
To develop Cloud applications successful you need to use novel architectures. We will cover principles like BASE and the CAP theorem. And we will show how to implement Cloud system with good scalability using RabbitMQ and a NoSQL database. Also Map/Reduce using Apache Hadoop will be demoed.
Of course there will be lot of live coding and material to take away so you can try it at home.
Take a look at the
official announcement (German) - looking forward to see you there!
Labels: Cloud, Cloud Foundry, Google App Engine, NoSQL, RabbitMQ, WJAX
Keynoting ECSA 2011
I feel honored to keynote with the subject "What Does it Really Mean to be an Architect?" the 5th European Conference on Software Architecture (ECSA 2011) in Essen, Germany. The conference takes place from 13-16 September 2011 to discuss the latest research and experiences in software architecture.
The range of topics includes service and component architectures, quality attributes of software architectures, product line architectures, management of architectural decisions, and enterprise architecture. Workshops on traceability and dependencies in software architecture, as well as software architecture variability, provide further opportunities for in-depth discussion.
Each day, keynote speakers from academic and industrial backgrounds will discuss perspectives on current trends and challenges in software architecture. The other keynotes are:
- Interactive Ubiquitous Computing Systems (Albrecht Schmidt, University of Stuttgart)
- Software Analysis as a Service (Harald Gall, University of Zurich)
- Enterprise Architecture (Jörg Koletzki, E.ON IT GmbH)
- Software Performance Engineering in Dynamic Environments (Raffela Mirandola, Politecnico di Milano)
- Balancing Long-Term Research with Industrial Applicability (Magnus Larsson, ABB Corporate Research)
The detailed program and registration information can be found at
http://www.ecsa2011.org - register online before August 14th to take advantage of the early registration rates!
Labels: ECSA2011, Keynote
Slides "Cloud Architecture" Online Seacon 2011
The slides for the talk "Cloud Architecture" from Seacon 2011 are online:
You can also
download them.
Labels: Cloud, Cloud Architecture, Seacon