Replacing Unsafe.allocateInstance

Henri Tremblay henri at
Mon Jun 29 16:02:57 UTC 2015

I do understand this is not the classical way to do an object. So it might
need to be protected even though the current way to do it are not that much.

It needs to be in the official API, like other Unsafe methods because it is
useful and needed. It is currently used by the serialization API. So other
frameworks that want to emulate the serialization should also be allowed
to. Right now they are hacking (for instance XStream) like Objenesis is
doing. JMock, Mockito and EasyMock are also hacking (using Objenesis or
something alike).

It's been more than 10 years. So, being pragmatic, not having to hack
around would be a great relief.

*Note:* We do not need to advertise it too much ;-) I'm don't plan to add
Object.allocateInstance. Maybe moving com.sun.deploy.util.ReflectionUtil to

I'm interested about performance because I do know some are using Objenesis
to instantiate objects quickly. I had some requests about that in the past.
However, I'm not sure that is still useful since my latest benchmarks are
showing that "new" is as fast. But indeed, 20ns is pretty fast.

On 27 June 2015 at 10:52, Andrew Haley <aph at> wrote:

> On 27/06/15 01:54, Henri Tremblay wrote:
> > The problems to solve seem to be:
> >
> >    1. Find a place to put the new method in the official java.* API
> >    2. Make it fast
> But Java is designed to stop people from creating objects without a
> constructor.  There are several places where this is required in order
> to guarantee security.  So I can't see much hope of it ever being part
> of the official API.
> As to why Unsafe.allocateInstance() is slow, I have to admit that's a
> mystery to me.  allocateInstance() should inline quite nicely.  I
> suppose it might be a little bit slower if HotSpot can't determine
> during compilation the class you're trying to create.  But I'm looking
> at and it should be fine.
> The only thing to do is to do some measurements and look at the
> generated code.  Mind you, 20ns is still pretty fast.
> Andrew.

More information about the jdk9-dev mailing list