Nagappa L M
Nagappa L M

Reputation: 1480

how using Lock interface gives more performance over using synchronise keyword in concurrent applications design?

I was going through "Java Concurrency CookBook". In that author mentioned using Lock interface gives more performance over using synchronized keyword.Can any one tell how? Using the terms like stack-frame, ornumber of method calls. Don't mind, please help me get rid of java concurrency concepts.

Upvotes: 5

Views: 133

Answers (2)

Aditya
Aditya

Reputation: 1058

1 Synchronisation is the only culprit that leads to the problem of deadlock unlike lock which is free of deadlock issue.

2 In synchronisation , we don’t know after how much time a thread will get a chance after a previous thread has released the lock. This can lead to problem of starvation whereas incase of lock we have its implementing class reentrant lock which has one of its constructor which lets you pass fairness property as one of its argument that leta longest waiting thread get the chance to acquire the lock.

3 In synchronisation, if a thread is waiting for another thread, then the waiting thread won’t do any other activity which doesn’t require lock access but with lock interface there is a trylock() method with which you can try for access the lock and if you don’t get the lock you can perform other alternate tasks. This helps to improve the performance of the application .

4 There is no api to check how many threads are waiting for a particular lock whereas this is possible with lock interface implementation class ReentrantLock methods.

5 One can get better control of locks using lock interface with holdCount() method which is not found with synchronization.

Upvotes: 0

user207421
user207421

Reputation: 310913

The raison d'etre for Lock and friends isn't that it is inherently faster than synchronized(), it is that it can be used in different ways that don't necessarily correspond to the lexical block structure, and also that it can offer more facilities such as read-write locks, counting semaphores, etc.

Whether a specific Lock implementation is actually faster than synchronized is a moot point and implementation-dependent. There is certainly no such claim in the Javadoc. Doug Leas's book[1] where it all started doesn't make any claim that I can see quickly stronger than 'often with better performance'.

[1]: Lea, Concurrent Programming in Java, 2nd edition, Addison Wesley 2000.

Upvotes: 2

Related Questions