Blog

Serialization of proxies

Occasionally, customers ask how to serialize proxies, particularly .NET-side proxies, as part of the functionality of the application they’re developing. They’ve noticed that the proxies are not [Serializable]. We’ve spent a fair amount of time thinking about this, and there are some interesting issues in proxy serialization.

First, let’s consider reference proxies. A reference proxy contains a “remote reference” to the underlying Java object. The problem with making a reference proxy serializable is that, if the proxy could be serialized somehow, just the remote reference would be stored away. Now, assume that after the proxy was serialized, the Java side was shut down. Later, when the Java side is started up again, there’s no guarantee that the underlying Java object will be created; if the proxy is deserialized, there there’s no guarantee that the remote reference will point to anything useful, or even anything at all.

Value proxies, on the other hand, are snapshots of the underlying Java object, and are more self-contained than reference proxies. So, in theory, it should be possible to serialize a value proxy. Yes, but some of the members of the value proxy can themselves be reference proxies, and can have the same serialization/deserialization problems we’ve just described. We could arbitrarily decide that only the non-reference members of a value proxy will be serialized, and not attempt to serialize the reference members, but it’s not always clear to the user/developer which members are reference and which are value. It can get complicated and lead to unexpected user errors, and we strive to keep things simple for the users and provide features that don’t encourage errors.

So what do you do if you really want to serialize the proxies? All is not lost. .NET provides a little-known but really cool feature called a serialization surrogate. It’s a way to specify serialization behavior for classes that weren’t designed to be serializable. Once you’ve created and registered a serialization surrogate for a given class, then that class is henceforth treated as serializable (as defined by the surrogate). There’s a great article on serialization surrogates here.