-->

How can i attach data to a JTA transaction? (or un

2019-06-24 06:23发布

问题:

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?

回答1:

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).



回答2:

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