ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?

user-image
تم إضافة السؤال من قبل Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
تاريخ النشر: 2014/02/17
مستخدم محذوف‎
من قبل مستخدم محذوف‎

java.util.concurrent api provides a class called as Lock, which would basically serializes the conntrol in order to access the critical resource.

If you're simply locking an object, I'd prefer to use synchronized

Example:

Lock.acquire(); doSomethingNifty();// Throws a NPE!Lock.release();// Oh noes, we never release the lock!

You have to explicitly do try{} finally{} everywhere.

Whereas with synchronized, it's super clear and impossible to get wrong:

synchronized(myObject){ doSomethingNifty();}

That said, Locks may be more useful for more complicated things where you can't acquire and release in such a clean manner. I would honestly prefer to avoid using bare Locks in the first place, and just go with a more sophisticated concurrency control such as a CyclicBarrier or a LinkedBlockingQueue, if they meet your needs.

 

I've never had a reason to use wait() or notify() but there may be some good ones.

المزيد من الأسئلة المماثلة

هل تحتاج لمساعدة في كتابة سيرة ذاتية تحتوي على الكلمات الدلالية التي يبحث عنها أصحاب العمل؟