Search code examples
javaspringserializationremotingidentity

How to preserve object identity across different JVMs


To be specific let me illustrate the question with Spring http-remoting example.

Suppose we have such implementation of a simple interface:

public SearchServiceImpl implements SearchService {
    public SearchJdo processSearch(SearchJdo search) {
        search.name = "a funky name";
        return search;
    }
}

SearchJdo is itself a simple POJO.

Now when we call the method from a client through http-remoting (Spring's mechanism of calling remote objects much like EJB that uses serialization) we'll get:

public class HTTPClient {
    public static void main(final String[] arguments) {
        final ApplicationContext context = new ClassPathXmlApplicationContext(
            "spring-http-client-config.xml");
        final SearchService searchService =
            (SearchService) context.getBean("searchService");

        SearchJdo search = new SearchJdo();
        search.name = "myName"; 
        // this method actually returns the same object it gets as an argument
        SearchJdo search2 = searchService.processSearch(search);
        System.out.println(search == search2); // prints "false"
    }
}

The problem is that the search objects are different because of serializaton although from logical prospective they are the same.

The question is whether there are some technique that allows to support or emulate object identity across VMs.


Solution

  • You said it - object identity is different from logical equality.

    • object identity is compared with ==
    • logical equality is compared with .equals(..)

    So override the equals() method and all will be fine. Remember to override hashCode() based on the same field(s) as well. Use your IDE to generate these 2 methods for you.

    (Teracotta VM clustering allows sharing objects between VMs, but that doesn't fit your case.)