Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Wednesday, August 13, 2008

Java transaction boundary tricks

Controlling transactions is one of the fundamental things you must control well if your program is to be used by more then 1 user and has a database (as in about every web application). This article shows a little trick to get more out of transactions then most programs do. Since I am using Spring to demonstrate the principle, I will introduce Spring's transactions first. Feel free to skip that section if you know all about Spring transactions.

Using transaction from Spring
With Spring, controlling where a transaction is started can be as simple as adding the @Transactional annotation (and one extra line in the Spring configuration). The @Transactional is typically placed on the class that implements the interface of your service layer. For example you may have a MemberService:

public interface MemberService { List findMembers(MemberCriteria criteria); Member getMember(long id); Member updateMember(Member member); }
with the following implementation:
@Transactional public class DefaultMemberService implements MemberService { public List findMembers(MemberCriteria criteria) { ... } public Member getMember(long id) { ... } public Member updateMember(Member member) { ... } }
When you let Spring instantiate DefaultMemberService as a bean, all of its public methods will be automatically proxied in such a way that the method is executed within a transaction.

Java transactions are bound to a thread (think ThreadLocal), the proxy can therefore join an existing transaction in the current call stack, and by default that is what happens. As a result you can safely call other transactional service methods from within your own transaction methods.

Introducing the CommandService
Here is a kind of weird service that I came up with a couple of years ago, named after the Command pattern, the CommandService:

@Transactional public class DefaultCommandService implements CommandService { public void inTransaction(Runnable command) { command.run(); } public <T> T inTransaction(Callable<T> command) { try { return command.call(); } catch (Exception e) { throw new RuntimeException( "CommandService#inTransaction(" + command.toString() + ")", e); } } }
(Download link at bottom of article.)

As you can see it doesn't to anything except for executing the runnable or callable it is given. How can this be useful? Well, notice the @Transactional. Your block of code is now executed within a transaction!

Again, how can this be useful? Here are 3 use cases:

Use case 1: prevent fine grained service methods
Suppose you have a webpage that will update only one property of an entity, e.g. the email address of a member, and another page to update the password. Now to prevent concurrent update problems you want to get and update the member within the same transaction. You could make a new method on the service interface for each property you want to change. However, it is a good practice to keep interfaces concise. So instead we do something like this:

final long memberId = ...; final String newEmail = ...; Member freshMe = commandService.inTransaction(new Callable<Member>() { public Member call() throws Exception { Member freshMe = memberService.getMember(memberId); freshMe.setEmail(email.getNewEmail()); return memberService.updateMember(freshMe); } });
The member entity is retrieved and updated in the same transaction. This way we only need 2 methods in the member service interface to safely update any property of a member.

Use case 2: bundle operations for performance reasons
I once wrote some code that would keep thousands of LDAP records in sync with a relational database. In my test environment, a dodgy laptop, it would take 50 minutes to do the initial import of 15,000 records. Each record was persisted to the database in its own transaction. After a small code change, I used the CommandService to persist the records in groups of 20. What do you think happened? The total time to import these 15000 records dropped from 50 to 2 minutes! Not bad, 25 times faster through 4 lines of extra code.

Careful positioning of transaction boundaries can have a dramatic effect on performance. CommandService can help you do that.

Use case 3: transactions in unusual places
Let us look at a little bit more detailed example of the PeriodicRetriever from my previous article (changes in italic).

public class CachingPostalCodeService { private final Object postalCacheLock = new Object(); private List<PostalCode> postalCache; private PeriodicExecutor postalCacheReloader; private HibernatePostalCodeDao hibernatePostalCodeDao; public CachingPostalCodeService() { postalCacheReloader = new PeriodicExecutor( TimeUnit.MINUTES.toMillis(10), new Runnable() { public void run() { refreshPostalCache(); } public String toString() { return "Postal code cache reloader"; } }); } public List<PostalCode> getPostalCodes() { postalCacheReloader.requestStart(); synchronized (postalCacheLock) { return postalCache; } } private void refreshPostalCache() { List<PostalCode> newPostalCodes = Collections.unmodifiableList( hibernatePostalCodeDao.getAll() ); synchronized (postalCacheLock) { postalCache = newPostalCodes; } } // ... setter for hibernatePostalCodeDao ... }
If you try this, you may notice that the data is retrieved the first time, but not the second time! The exception message is clear too, something like "Hibernate requires a transaction". To understand this lets follow the two execution paths.

The first time getPostalCodes() is called, it is called through Spring's transaction proxy, so the method is executed within a transaction. So when the PeriodicRetriever is called, the runnable (which calls refreshPostalCache()) is immediately called within the same thread and thus also within the same transaction. No problem!

The second time getPostalCodes() is called (11 minutes later), PeriodicRetriever is called again but returns immediately. Meanwhile it starts a new thread which executes the runnable defined in CachingPostalCodeService's constructor. The important thing here is that the new thread does not join the transaction of its parent thread as transactions are bound to threads. The runnable then calls refreshPostalCache(). You may think you'll get a new transaction at that moment. However, a method call within the same class will never go through the transactional proxy. This is because the instance on which we call refreshPostalCache() is simply this, and not the proxy that was obtained from Spring. In other words: refreshPostalCache() is not executed within a transaction.

CommandService to the rescue (again, changes in italic):

public class CachingPostalCodeService { private final Object postalCacheLock = new Object(); private List<PostalCode> postalCache; private PeriodicExecutor postalCacheReloader; private HibernatePostalCodeDao hibernatePostalCodeDao; private CommandService commandService; public CachingPostalCodeService() { postalCacheReloader = new PeriodicExecutor( TimeUnit.MINUTES.toMillis(10), new Runnable() { public void run() { commandService.inTransaction(new Runnable() { public void run() { refreshPostalCache(); } }); } public String toString() { return "Postal code cache reloader"; } }); } // ... same as above ... // ... setters for hibernatePostalCodeDao and commandService }

Download
Feel free to use the complete version of CommandService in any way you see fit.

Conclusions
Watching your transaction boundaries can be very rewarding, both in code size as in performance. A command service, such as the one presented in this article can help you do that.

Thursday, July 24, 2008

Spring message resource weirdness

Today I got a bug report that e-mail subject appeared in Dutch while they should have been send in English. The first thing I check of course was whether the correct locale was used. It was.

Here is the situation:

  • Spring message source
  • 2 files: email-subjects.properties and email-subjects_nl.properties
  • requested locale: en_US
After a bit of debugging I noticed that Spring looks for the following files (in order):
  1. email-subjects_en_us.properties
  2. email-subjects_en.properties
  3. email-subjects_nl_NL.properties
  4. email-subjects_nl.properties
  5. email-subjects.properties
WTF?! It also looks for the default locale! Thank you Spring! This is really the first time you disappoint me (in 4 years, not bad). But of course I should have looked further, when will Spring ever let you down?

The solution? Well luckily the authors of the code realized this is not always what you want. An easy setFallbackToSystemLocale(false) overrides this funny behavior. I added <property name="fallbackToSystemLocale" value="false" /> to my config file and it all worked. Hurray for Spring!

Update 2008-08-04: adapted the article to the real solution.

Thursday, April 26, 2007

Spring integration test hacking

Update 2007-05-01: You probably can not follow this article if you did not work with Spring tests yet. The key to this article is at the end, where I show how to call an injected object while it has been proxied by Spring.
A colleague (Levi Hoogenberg) showed me a working example of integration tests with Spring. The key is to make a JUnit test that inherits from AbstractAnnotationAwareTransactionalTests (they like long names at Spring). Simply override getConfigLocations() and a complete spring context will be loaded. Any setters in your test class will automatically be called with beans from the context (called auto-wiring). In addition, you can execute some SQL to initialize a database (for example by calling executeSqlScript() in onSetUpBeforeTransaction()). Each test gets a fresh view at the filled database and runs in a fresh new transaction.

My main spring configuration (in spring.xml) sets up a context with all the services and its Hibernate backend. The MySQL database connection is set up in a separate file (spring-db.xml). The test however, is not using MySQL but an in-memory H2 database so that it can easily be run from Continuum. This is configured in another file (spring-test.xml).

A big advantage of this setup is that it allows you to test most of the real application wiring. Disadvantage is that it uses Hibernate against H2 and not the MySQL target database. I am not too worried about this, I am not using advanced Hibernate features and I do not have to test Hibernate!

So I was happily writing tests until I found out that one integration test went much too far. The service I was trying to test (lets call it AbcService) did more then just save something in the database; it also called another service to schedule a task. In a real integration test I would need to assert that the task would have been scheduled. I realized that I was actually misusing the integration test to also do a unit test on AbcService. Instead of writing a proper unit test, I decided to leave it at that.

So how was I going to assert that the scheduler service was called? Here are my attempts:

Solution 1: Test specific config files
Since you can not override a small part of the configuration, this solution requires you to duplicate a lot of configuration files. Furthermore, you loose the ability to test the actual application configuration files. As soon as I realized this I gave up on the idea.

Solution 2: Override the configured service by changing the setter in the test class
The test class (AbcServiceImplTest) has a setter to inject the service under test like so:

public void setAbcService(AbcService abcService) { this.abcService = abcService; }
Pretty standard. So my idea was to override the used scheduler service like this:
public void setAbcService(AbcService abcService) { this.abcService = abcService; // Override the scheduler service with a mock SchedulerService mockSchedulerService = ... ((AbcServiceImpl) abcSerive).setSchedulerService( mockSchedulerService); // Cast fails! }
Unfortunately, the passed in abcService is not the real thing. It has been proxied by Spring to add transaction support. The proxy that Spring uses (the standard JDK proxy) can only be casted to the implemented interfaces, and not to an actual class.

After a lot of searching and looking with the debugger, I finally found a solution. Be warned: this is a big hack. Do try this at home, but don't complain when it suddenly fails.

public void setAbcService(AbcService abcService) { this.abcService = abcService; // Override the scheduler service with a mock SchedulerService mockSchedulerService = ... InvocationHandler invocationHandler = Proxy.getInvocationHandler(abcService); try { invocationHandler.invoke( abcService, AbcServiceImpl.class.getMethod( "setSchedulerService", new Class[] {SchedulerService.class}), new Object[] {mockSchedulerService}); } catch (Throwable e) { fail("setSchedulerService failed"); } }
Incredible, isn't it?