Java – How to synchronize client and server model objects

gwtjavamvcmvp

We have a client-server application with a thick client (GWT).

There are client-side MVP presenters (MVC controllers) which hold references to some objects viewed in the GUI. Some user actions cause these objects to be updated on the server. After that we can send updated objects back to the client and reassign them to the presenter.

The problem is that there are usually a few references to an object on the client (Lists, HashMaps, etc.) and it is hard to update all of them.

Another approach is not to update the references but update the object itself, e.g. copy all the properties from the server object to the client one. But if an object is complex it is not easy too.

Which approach is better? Or maybe I miss something?

Best Answer

This problem is almost identical to the synchronization one maintain between its code and the database.

Usually, backend code do the same workflow:

  1. Request database
  2. Create (hydrate) object from raw data
  3. Manipulate data
  4. If needed, update the database.
  5. On the next request (in the case of a web app), you totally invalidate the hydrated objects you have, an begin from point 1. again, as you recognize the database to be the "upstream" source of the data.

From there, I'd say you have 2 paradigms:

Client - server like Server - database

Client to server sync is pretty much the same, you need to setup some cycle, where you consider that your data are still "fresh", then upon the next "action" of your user, query again the server (as you would do with a database), and create your client objects from there.

Push from server to client

Another solution is to have the server "push" the new object states to the client, as soon as it know they have been updated. Such paradigm is use by new frameworks like Meteor: servers listen to the database, wich emit an event upon every update/insert/etc. Servers then update their internals objects, and transmit the event to clients, which do the same (I'm simplifying for the sake of the answer).

Conclusion

In any case, there's no universal solution that you need to add as a library to your project. Caching is hard, like real hard, and you'll need to integrate the server - client constraints to your code, and handle such cache yourself.

Related Topic