Let's consider two classes:
Airport that has a field code.
AirportFinder with two methods:
- loadCache --- reads all the airports from database and puts them into distributed cache with codes as cache keys
- findByCode --- obtains instance of Airport from cache by its code.
loadCache is called during application startup and all subsequent calls of findByCode use populated cache.
Now let's say we want to pass instances of Airport between virtual machines but preserve their uniqueness in a sense that every airport instance is actually from cache. So we could to add method readResolve like this:
private Object readResolve() {
return airportFinder.findByCode(code);
}
The problem is however that findByCode obtains object from distributed cache and deserializes it. This causes readResolve to be called again on that object which gives never-ending recursion.
The question is how to achieve the uniqueness of Airport objects across JVM in this case? I use Tangosol Coherence.