Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReentrantReadWriteLock vs synchronized

When should we use ReentrantReadWriteLock as compared to synchronized keyword in multithreaded environment in Java?

What are the benefits of using ReentrantReadWriteLock over synchronized in Java?

Can any one give an example as well (in Java)?

Thanks!

like image 718
Mike Avatar asked Jul 09 '11 20:07

Mike


1 Answers

Synchronized allows in one thread at a time.

Read/Write locks allow in multiple readers a the same time, but only if no writers are already in. Hence under some usage scenarios we can get better concurrency, because the reader populations can proceed together.

Java API documentation gives the example of collection classes which are expected to have more readers than writers.

like image 63
djna Avatar answered Sep 29 '22 08:09

djna