Stateful Service Operations

Now let us demonstrate how to manage state in the Service instances and how to instruct GridServer to behave properly under these operating conditions. First, let’s consider the following bond calculator class that holds state:

public class BondValuationService {
    public void addBonds(String[] bondIds) {…}
    public void setBonds (String[] bondIds) {…}
    public ValuationResults valueAllBonds(Scenario s) {…}
}

Both the addBonds and setBonds methods take a list of bond IDs. We assume that in these methods the actual object representations are constructed and the bond data is fetched from an appropriate source and loaded into the object representations. We further assume that there is a fair amount of latency and computation involved in these object constructions—this is why the writer of this Service is interested in keeping this stateful data present in the Service. There is also a stateless computing method that computes the valuations for these financial instruments under different market conditions or scenarios.

In this example, we see that there are two stateful methods—addBonds and setBonds. But their behavior is different: if addBonds is called, the new bonds are added to the existing collection, while the setBonds method replaces the existing collection. One can capture this distinction and ensure proper behavior of the GridServer deployment by setting the appropriate fields in the ContainerBinding section of the Service Types page. There is a field called appendStateMethods that can be set to the value addBonds and a field called setStateMethods that can be set to the value setBonds. More than one method can be listed, separating them by commas.

The client-side proxy class generated by GridServer looks quite similar to the actual Service:

public class BondValuationServiceProxy {
    public void addBonds(String[] bondIds) {…}
    public void setBonds (String[] bondIds) {…}
    public ValuationResults valueAllBonds(Scenario s) {…}
}

However, if you are using the Service API, you have to make the distinction in the API calls themselves. Notice the following use of the method updateState:

Service service = ServiceFactory.getInstance().createService("bondCalculator");
service.updateState("addBonds", new Object[] { bondIds }, false);
// or
service.updateState("setBonds", new Object[] { bondIds }, true);

The last argument to the updateState method is a Boolean that indicates whether this state must replace the current state (true) or append the current state (false).