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?
This would require some testing but I think that you could bind the quote to a
ThreadLocaland make your beans implementSessionSynchronizationto unbind the quote from theThreadLocalafter the commit of a transaction (and thus implement a kind of transaction-scoped context).