Ensuring consistency in in-memory data structures

134 views Asked by At

I was wondering what would have been the best way (probably I am looking for a pattern) to ensure data consistency in an everyday example where a service retrieves data by invoking some method on a gateway (the gateway might be the boundary for DB, a web call or even an in-memory data structure).

Here is an example of the case I described in Java:

public class MyService {

    private DataSourceGateway dataSourceGateway;

    public MyService(DataSourceGateway dataSourceGateway) {
        this.dataSourceGateway = dataSourceGateway;
    }

    public void myServiceMethod() {
        doThings1();
        doThings2();
    }

    private void doThings1() {
        int count = dataSourceGateway.getCount();
        // do things with this count
    }

    private void doThings2() {
        int count = dataSourceGateway.getCount();
        // do things with this count which is expected to be the same as in doThings1()
    }
}

Let's assume that DataSourceGateway might not be a database that offers transactions, but an in-memory data structure and DataSourceGateway and Service are Singletons.

The obvious consistency problem would be when another service modifies the data in DataSourceGateway when a call to myServiceMethod() has completed doThings1() and is about to execute doThings2().

The example is simplified but consider the cases when not the same method on dataSourceGateway is called but also calls on objects that have some dependencies (e.g. getCount and getAll should be consistent). The reason I called this an everyday problem is because I have seen the same DataSourceGateways (or DAOs) being injected in multiple places and usually the developer expect that the calls would be consistent.

What would be the best way to ensure that count would be the same these 2 calls?

0

There are 0 answers