February 04, 2009

TringMe steals idea for Silverlight + VOIP demo and claims to be "first"

TringMe needs to do some research before they post claims about being the first to leverage VOIP in a Silverlight application...

http://blog.tringme.com/first-voip-demonstration-on-microsoft-silverlight/

"We are happy to announce a first ever demonstration of VoIP/Telephony over Microsoft Silverlight platform at..."

This was already done back in April 2008 at the PhizzPop National Championships by some of my colleagues at Cynergy. Right from Microsoft's own web site:

http://www.microsoft.com/presspass/features/2008/apr08/04-17phizzpop.mspx

"The winner was Washington, D.C.-based Cynergy Systems, whose solution, “ben,” is a series of interconnected, cross-platform applications based on Microsoft Silverlight, Windows Presentation Foundation, Live Services, Twitter and voice-over-IP (VoIP) technologies. Cynergy won the People’s Choice award as well."

January 03, 2009

New Year, New Blog URL

I've upgraded my TypePad account such that you can now access the blog directly via the proper URL:

http://histos.net/

The old URLs will also continue to work:

http://histos.typepad.com/

http://histos.typepad.com/blog/

Feel free to update your blogrolls, etc accordingly. Thanks and have a Happy New Year!

December 17, 2008

Mixing and Matching Spring JdbcTemplate and HibernateTemplate

The JdbcTemplate and HibernateTemplate convenience classes from Spring really make working with the respective APIs a breeze. Unfortunately getting both of these classes to work together within a single Transaction is not straightforward. This comes up very frequently in JUnit tests where you want to verify Hibernate is working with the database in the way you expect, either by inserting data and letting Hibernate load it or by checking to see that Hibernate creates the data you expect. The same will hold true in application code where you need to add JDBC code alongside Hibernate code to meet various requirements. The testing scenarios are simple and illustrative so let's explore those.

One common use case is to persist an object with HibernateTemplate and then verify the data was inserted correctly using JdbcTemplate. Usually Hibernate will not flush the data out to the DB until the transaction commits, meaning that the query done by JdbcTemplate won't be able to see the new data. This one isn't hard to work around: just call HibernateTemplate.flush() to execute the SQL on demand so that subsequent calls to JdbcTemplate will see the new data.

The second use case is a lot tricker: let's say you want to create some data with JdbcTemplate and then make sure that calls to HibernateTemplate will see that data. By default this will not work. You can actually insert with JdbcTemplate, make a call to load the data with HibernateTemplate (it won't find it) and then make another call to JdbcTemplate which will show that the data is there. The problem is that since JdbcTemplate is injected with a DataSource it doesn't really have any knowledge of the transactions from HibernateTransactionManager; thus operations from the two templates are isolated from one another.

Fortunately Spring offers a solution in the TransactionAwareDataSourceProxy class. Just like the name imples, this class acts as a wrapper for an existing DataSource so that all collaborators will participate in Spring-managed transactions. Configuration of this class is trivial:

<bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
    <property name="targetDataSource">
        <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
                ...
        </bean>
    </property>
</bean>   

Note: you may or may not want to define the "real" DataSource as an inner bean that doesn't get registered in the ApplicationContext itself. If you are autowiring your DataSource purely by type, having two different implementations of DataSource will be a problem for you. Workarounds include autowiring using @Qualifier or using @Resource to inject the bean by name.

December 03, 2008

On Hibernate, Spring, Sessions and Transactions

I was recently working with Spring and Hibernate on a pet project and ran into some issues with Session and Transaction management that proved to be pretty interesting in the end. The following assumes a working knowledge of Hibernate and Spring...

I was in the midst of writing some JUnit 4.x tests using SpringJUnit4ClassRunner and the @TransactionalConfiguration / @Transactional annotations for automatic rollback of @Test methods. I wanted to do some manipulation of the database prior to my tests using a separate method annotated with @Before. What I was reminded of very quickly is that Spring's class runner will not apply a transactional aspect to this method since it's not actually a @Test. This isn't a problem if you are using HibernateTemplate / HibernateCallback, since it ultimately has a reference back to your TransactionManager to handle transactions. But if you want to work with the raw Hibernate APIs it can be problematic.

There are two things to keep in mind: (1) SessionFactory.getCurrentSession() will only work if you have configured the SessionFactory appropriately, and (2) depending on the configuration, you may have to manage Transactions explicitly. The configuration property in question is "hibernate.current_session_context_class" and it is commonly configured one of three different ways:

1. Omitted the property from the configuration

Hibernate will throw an exception on calls to getCurrentSession() complaining that there is no CurrentSessionContext configured.

2. Configured with 'thread'

hibernate.current_session_context_class=thread

Hibernate will bind the Session returned from getCurrentSession() to the current thread and you must manage transactions programmatically. Generally all that's required is to call Session.beginTransaction(). You can also invoke Transaction.commit() or rollback() if you wish.

3. Configured with SpringSessionContext

hibernate.current_session_context_class=org.springframework.orm.hibernate3.SpringSessionContext

Hibernate will assume it is executing inside of a Spring transactional context (i.e. through a Spring transactional aspect) and Spring will now manage your transaction for you. However if you call getCurrentSession() outside of such a context, Hibernate will throw an exception complaining that no Session is bound to the thread.

What does all this mean?

  1. Use SpringSessionContext if your operations will be done through classes that are invoked through a Spring-managed transactional context or if you can introduce HibernateTemplate and/or HibernateCallback wherever you need it.
  2. Use "thread" if you need to raw with the raw Hibernate Session/Transaction API and remember that you'll need to manage transactions programmatically.

October 13, 2008

Book Review: The Definitive Guide to Terracotta

Terracotta is a “transparent clustering technology” that allows you to make data structures available across a cluster of machines in a highly-scalable and robust manner. Unlike many other clustering solutions (including the very popular memcached), it doesn’t expose an API that a developer leverages to push data structures in and out of a big distributed container. Rather, it’s a library that’s boot-strapped into your JVM while the behavior is driven by an XML config file. This allows for sharing data in the fields of a class across the cluster as well as synchronized access to objects, just like in any multithreaded application. Terracotta is able to do this through some very interesting decoration of bytecode as Java classes are loaded into the JVM. What this ultimately allows for is something like a large shared memory heap shared by all JVMs which can survive JVM crashes since all data is also written to disk. Additionally, since Terracotta doesn’t use a peer-to-peer approach of data replication, it’s easier to achieve linear scalability.

Sound interesting? Learn more at the Terracotta web site.

This is an excellent book. The prose is well-written and engaging and the book flows very well from section to section. There are massive amounts of Java code and configuration such that you very rarely have to picture anything in your mind, you can just read it there on the page. There are helpful diagrams where appropriate. It’s unlikely that a reader with a good understanding of Java will become confused at any point during the book. It’s informative and provides some excellent examples of real world use, including especially chapters on integration with things like like Spring, Hibernate, session replication and more. There is also an extensive chapter on using Terracotta to create a Master/Worker compute grid. If you’re looking to learn more about Terracotta I really can’t recommend this book enough: it helped fill so many gaps that I had after skimming some of the documentation and reading a few of the white papers.

The only real negative is that the book is slow to get started. The first two chapters (~40 pages) serve as an introduction and history to the technology respectively but taken together, it’s just a very lengthy introduction that rehashes a lot of the same concepts. Maybe this was tedious for me given that I’d already read a lot of documentation on Terracotta but it just seemed like the intro could have been a bit shorter.

I’ll now run down the other chapters in the book and detail some that I found particularly interesting.

Chapter 3 is a quick jump into the framework and some tooling while Chapter 4 gets into the nitty-gritty details of POJO clustering. This is important to read to understand how Terracotta does what it does. Chapter 5 talks about how to do caching and this is where you start to understand the real world problems that can be solved using the tool. Your database will thank you!

Chapter 6 is where it gets really interesting. Here you will learn how to use Terracotta as a 2nd-level cache provider for Hibernate to significantly boost performance over using something like Ehcache . More startling than that is a proposed architecture where the notion of POJO clustering is used to effectively put data structures that hold detached objects (those not attached to an active Hibernate Session). You are shown how to change application code that uses the Hibernate API in a “typical” fashion to achieve performance increases measured in orders of magnitude. This is truly an eye-opener.

Chapter 7 shows you how to cluster HTTP Sessions and how you can be freed from some of the annoying restrictions of the Servlet container Session API, such as implementing Serializable and religiously using setAttribute(). ; This is the sort of thing you can plug into an existing application very quickly and realize enormous scalability gains.

Chapter 8 is about clustering Spring beans. Spring and Terracotta follow a very similar philosophy in that they are non-invasive frameworks. As such, they compliment each other very nicely. This chapter shows how easy it is to cluster Spring beans: even easier perhaps than clustering POJOs as in Chapter 4. At this point, if you are a user of Spring and Hibernate, you’re starting to see how easy it can be to achieve seriously scalability and performance improvements.

Chapter 9 talks about Terracotta Integration Modules which is a sort of package that provides additional features to the Terracotta core: this is how integration with Hibernate and Spring are achieved. Chapter 10 gives an extended treatment of thread coordination, showing how well-written multithreaded code can be used with Terracotta to achieve thread coordination across multiple JVMs. Chapter 11 takes this further to detail the Master/Worker pattern for computing grids. Chapter 12 rounds things out by showing the visualization tools that can be used to monitor and debug an app using Terracotta.

As I said before, this is a great book. If you’re interesting in scaling out enterprise Java applications, you owe it to yourself to check out Terracotta and this book.