A
A
andreycha2011-04-17 00:26:46
Java
andreycha, 2011-04-17 00:26:46

synchronized in Java (Android)

I was leafing through my notebook and found a recording from an Android seminar, from the optimization tips section, and I quote:

synchronized on new object[0] is more efficient than on new object

those. It's better to lock an empty array of objects than the object itself.

Question: why?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
apangin, 2011-04-18
@apangin

I know for sure that in Oracle VM synchronization on Object and Object[0] is no different. I just looked at the Dalvik VM sources - the same thing is there. An array of objects is a special case of an object, and the dvmLockObject function treats all objects in the same way.
Maybe the difference was in the new operation? When creating new Object(), the bytecode contains a call to the Object.<init> constructor, while an array does not have a constructor. Thus, in the interpreter, new Object[0] will indeed be faster. However, with the advent of the JIT compiler in Anroid 2.2, the empty Object() constructor is not called, and again there will be no difference.

R
romik, 2011-04-17
@romik

As for efficiency, I doubt it, but there may be a reason that new Object[0] is serializable, but new Object() is not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question