views:

29

answers:

2

I have a getStockQuote() function that will get a current stock quote for a symbol from the stock market.

My goal is that within a JTA transaction, the first call to getStockQuote() will fetch a stock quote, but all subsequent calls within the same transaction will reuse the same stock quote (e.g.: it will not try to fetch a new quote). If a different transaction starts, or another transaction runs concurrently, i would expect the other transaction to fetch its own stock quote on its first call.

This is to try to ensure consistency within the transaction - so that all calculations within the transaction are based on the same stock price.

This would be similar to how you can configure JPA providers to only fetch a database row from the database once, and use the cached value for subsequent access to the same database row within the transaction.

Does anyone have tips on how this can be achieved?

A: 

This would require some testing but I think that you could bind the quote to a ThreadLocal and make your beans implement SessionSynchronization to unbind the quote from the ThreadLocal after the commit of a transaction (and thus implement a kind of transaction-scoped context).

Pascal Thivent
My understanding is a single thread can be used for two transactions - for example: transaction A starts, i fetch a stock quote, i use the cached stock quote, transaction A ends. transaction B then starts in the same thread, how would i know that i need to fetch a new quote?
kwyjibo
this is where SessionSynchronization comes in. In your afterBegin() method you initialize the object and in afterCompletion() you terminate it (actually only initializing it will be enough, unless you need to close any resources)
seanizer
The SessionSynchronization interface was exactly what i was looking for, thanks.
kwyjibo
@seanizer Agreed, initializing things in `afterBegin` should suffice here.
Pascal Thivent
A: 

consider using spring for transaction management, it provides this functionality out of the box:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#tx-propagation

seanizer
I cannot see any reference to storing custom data in that documentation
kwyjibo
let me rephrase this: it provides the tools needed to create such functionality. Custom transaction managers, transaction callbacks, helper utilities to look up the current transaction, there are many ways to do it. Sorry for inadequate answer
seanizer