Java cache with transactions

I would like to have a simple cache that supports transactions. With simple ones I mean that I just want to load all data on startup and does not require an eviction. (a simple card will do).

However, it should support transactions like this, if the database crash fails, the changes made to the cache are rolled back as well.

I've heard about JTA, but it seems too big for what I need. It would be nice to manually roll back the cache if SQLException is thrown into the database transaction.

Are there any options?

If not, can someone point me to a good tutorial about JTA? eg. examples and what packages / classes are required. Note. I am creating a framework so that it can work standalone without an app container.

EDIT:

Forgot 1 very important question:

Cached objects are immutable! Updating means replacing it with a new object equal to the old one (method equal to id methods).

EDIT 2:

Wrote JPA instead of JTA ...

EDIT 3:

Explanation why simple map doesn't work:

I have 2 types of entities. I will call them Compound and Element. A compound can have multiple items, and each item can appear in multiple compounds. The items are managed by my infrastructure. For example, only connections can be added. The user adds a new connection by specifying its members. The framework then selects and leaves an element and associates it with a new connection or creates a new element.

I am caching all items where each item contains a set of Compound IDs where that item occurs. This is because the structure performs a special kind of search (for example, isomorphism of subgraphs). For each such search everything !!! dataset (all items) needs to be loaded from the database, hence the cache.

Therefore, if a new connection was added or updated, the items touched in the cache must also be updated.

Decision:

What I said in the comments: - keep the IDs (= integers) of all changed objects in memory and then update only the ones that were changed after the database transaction.

private void updateSearchCache(Collection<String> changedIds,
        Connection connection) {

    synchronized (searchCache) { 
        for (String id : changedIds) {
            Object myObject = getSearchObject(id, connection);
            searchCache.put(id, myObject);
        }
    }
}

      

+3


source to share


3 answers


Can't you just put your data in Map

after the transaction is committed to the database, can you?



So, yours Map

will only contain the data that is already in the database.

+2


source


Berkeley DB can be used to create in-memory tables and have transactional support .



This is a great choice if what you want to store is blob-> blob mappings, but not an object cache.

0


source


Transactional caching is possible with infinispan . Although designed as a clustered cache, it can easily run on a single machine . The cache-up extends java.util.Map and is easy to use.

0


source







All Articles