Replacing Unsafe.allocateInstance

Christoph Engelbert chris at hazelcast.com
Sun Aug 2 07:52:05 UTC 2015


Hey Paul,

The assumption of non creating JDK classes without calling constructors is not completely right.
Seen serialization frameworks that create String instances and “injecting” a char[] afterwards however I prefer calling the package private constructor to just prevent copying of the char[] (in cases where it won’t break the immutability contract like deserialization).

Chris

> Am 30.06.2015 um 12:22 schrieb Paul Sandoz <paul.sandoz at oracle.com>:
> 
> Hi Henri,
> 
> Thanks for raising this discussion.
> 
> Just to augment what Chris says here.
> 
> We cannot directly expose Unsafe.allocateInstance in a public API and try and place in a little known corner and hope only the people who are meant to use it will and will do so responsibly :-)
> 
> There are a bunch of general use-cases:
> 
>  1) Mocking;
>  2) Proxying; and
>  3) Serialization.
> 
> It should be possible to corral 3 (and possibly 2) in some safe mechanism. I dunno how to do that for 1.
> 
> Constructing an object without calling its constructor is inherently integrity busting (unless somehow hidden or contained) and IIUC mocking by design is a form of semi-controlled integrity busting.
> 
> Would i be correct in assuming that mocking is primarily used for testing and that if used in production would raise some eye brows?
> 
> One approach we could consider for 1, trying to be pragmatic and recognising the reality here, is a method that constructs an object without calling it's constructor under the following conditions:
> 
> 1) a security check is performed if a security manager is present; and
> 
> 2) it would not be possible to construct any JDK class (e.g. classes loaded by the boot loader).
> 
> That is not a definite proposal but i would be really interested in your feedback given your experience with Objenesis and mocking.
> 
> Paul.



More information about the jdk9-dev mailing list