The Roy
The Roy

Reputation: 2208

Is using explicit locks considered expensive?

It is mentioned that using an explicit lock declaration for object level lock as the one below is a good practice. However, I think for every instance of the object that we create we will end up creating a new object for the lock and access our method via a lock which are both expensive steps.

However, in the case of synchronized method, I believe there isn't any such thing as you are using object's own lock and you only pay the cost of acquiring a lock. You avoid the creation of an explicit lock object.

Am I missing anything here?

public class DemoClass
{
    private final Object lock = new Object();
    public void demoMethod(){
        synchronized (lock)
        {
            //other thread safe code
        }
    }
}

Upvotes: 2

Views: 782

Answers (1)

Stephen C
Stephen C

Reputation: 718836

Is using explicit locks considered expensive?

Generally, no. It is not considered expensive. (Modulo that different people have different opinions, and different applications have different requirements.)

The cost of a lock Object instance is about 8 bytes of memory plus the memory for the variable holding the reference to the lock in the parent object. That is 12 or 16 bytes in all.

The cost of creating a lock Object instance is ... a few nanoseconds. (Not exactly sure how many, but it is trivial.)

The cost of reclaiming a lock Object instance when it becomes garbage is typically zero. (The GC costs are incurred when the lock and its parent object are not garbage ...)

These costs are all insignificant unless you have millions of these objects or an excessive object turn-over rate or you have severe memory or latency constraints.

(Or if you have decided to put / use locks on things that don't need to be locked. But that is a different problem.)

There is (AFAIK) minimal difference in the cost of acquiring or releasing a lock on an explicit lock object versus acquiring / releasing the lock on this. Maybe one memory access.


For a typical application these cost differences won't matter. There will be more important things to optimize. The standard advice applies:

  • Code it simple1 to start with. Simple is easier to write and debug ... and read.
  • Avoid optimizing too soon; e.g. while you are writing the code.
  • Benchmark and profile your application before you optimize.
  • Use the results of the measurements to decide what is worth optimizing.

The performance issues probably pale into insignificance compared with the potential problems that can be caused by locking on this. In reality, it depends on your application complexity and implementation details.


1 - Simple enough for you and your co-workers. It is context dependent.

Upvotes: 3

Related Questions