Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use the same lock object at two different code block?

Tags:

Can I use the same lock object at two methods, accessed by two different threads? Goal is to make task1 and task2 thread safe.

object lockObject = new object();  // Thread 1 void Method1() {     lock(lockObject)     {         // task1     } }  // Thread 2 void Method2() {     lock(lockObject)     {         // task2     } } 
like image 583
RedFox Avatar asked Feb 22 '12 23:02

RedFox


People also ask

Can I use the same lock object in two different ways?

26 Yes, you can use the same lock object (it's technically a monitorin the computer science sense, and is implemented with calls to methods in System.Monitor) in two different methods.

Can you execute multiple blocks at the same time?

You can and it works. If you don't use the same object, the blocks could execute at the same time. If you do use the same object, they can't.

What is object-level lock in Java?

Object-level lock: Every object in java has a unique lock. Whenever we are using a synchronized keyword, then only the lock concept will come into the picture. If a thread wants to execute then synchronized method on the given object.

What are the types of locks on threads in Java?

In synchronization, there are two types of locks on threads: Object level lock : Every object in java has a unique lock. Whenever we are using synchronized keyword, then only lock concept will come in the picture. Class level lock : Every class in java has a unique lock which is nothing but class level lock.


1 Answers

Yes, you can use the same lock object (it's technically a monitor in the computer science sense, and is implemented with calls to methods in System.Monitor) in two different methods.

So, say that you had some static resource r, and you wanted two threads to access that resource, but only one thread can use it at a time (this is the classic goal of a lock). Then you would write code like

public class Foo {     private static object _LOCK = new object();      public void Method1()     {         lock (_LOCK)         {             // Use resource r         }     }      public void Method2()     {         lock (_LOCK)         {             // Use resource r         }     } } 

You need to lock around every use of r in your program, since otherwise two threads can use r at the same time. Furthermore, you must use the same lock, since otherwise again two threads would be able to use r at the same time. So, if you are using r in two different methods, you must use the same lock from both methods.

EDIT: As @diev points out in the comments, if the resource were per-instance on objects of type Foo, we would not make _LOCK static, but would make _LOCK instance-level data.

like image 122
Adam Mihalcin Avatar answered Nov 13 '22 12:11

Adam Mihalcin