Monday, January 9, 2012

Chapter 12: Choosing a Locking Mechanism

After reading the previous chapters on locks and synchronization, you may be wondering, how would I choose a locking mechanism for my multi-threaded code?

Well, before we answer this doubt, using synchronized methods or blocks is much easier than using the explicit locking mechanism. Using the synchronized keyword, you need not manually grab and release the lock so, the chances of any unexpected exceptions are very minimal (unless your code has a hole through which I can drive a truck, the usage of synchronized keyword does not cause exceptions by itself)

Ok, coming back to the answer, it is possible to use explicit locking for everything. It is possible to code to just use the synchronized keyword. And it is possible to use a combination of both. Avoid using the explicit locking unless you are writing extremely complicate code. In such extreme circumstances, the explicit locking mechanism offers a much better array of features than the standard synchronized keyword. So, the simple answer is “Take a judgment call based on the scenario. If you want to keep it simple, use the Synchronized keyword and for complicated scenarios use explicit locking”

At the end of the day, which technique to use is often a matter of personal preference.

Previous: Lock Scope

Next: Nested Locks

No comments:

Post a Comment

© 2013 by All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.