You can find equivalent APIs in Lock and Object
public void lock()
Acquires the lock.
public void unlock()
Attempts to release this lock.
Sample code:
class X {
ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
assert !lock.isHeldByCurrentThread();
lock.lock();
try {
// ... method body
} finally {
lock.unlock();
}
}
}
Main different: You are calling static
methods by passing the object to Monitor
class. In Java, you have to execute the methods on instance ( ReentrantLock
or Object
) and hence passing of object is not required.
Mapping of Monitor
in c# with Lock
class in java
Enter(this) => lock()
Exit(Object) => unlock()
TryEnter(Object) => tryLock()
TryEnter(Object, TimeSpan) => tryLock(long timeout, TimeUnit unit)
Mapping of Monitor
in c# with Object
class in java
Wait(Object) => wait()
Pulse(object obj) => notify()
PulseAll(Object) => nofityAll()
Regarding other query:
synchronized(this) {
//do something
}
is similar but not the same.
Related question : Why use a ReentrantLock if one can use synchronized(this)?