testCoder
testCoder

Reputation: 7385

Monitor.TryEnter equivalent in Java

How to skip method if some thread owns by this method in java, i know that in .net exists Monitor.TryEnter, and i can accomplish that by something like this:

if(Monitor.TryEnter()){
 //do work
}
//else skip

But how can i accomplish that behavior in java, is any equivalent of Monitor.TryEnter in java.

Upvotes: 2

Views: 966

Answers (2)

bowmore
bowmore

Reputation: 11280

I think you're probably best off using java.util.concurrent.Semaphore.

If you use a Semaphore that holds one permit :

Semaphore semaphore = new Semaphore(1);

the resulting code looks virtually the same :

if (semaphore.tryAcquire()) {
    try {
        // do work
    } finally {
        semaphore.release();
    }
}
// else skip

I imagine in .Net you also have to make sure to release the lock again.

Upvotes: 1

thkala
thkala

Reputation: 86353

Would ReentrantLock#tryLock() work for you?

It has the behavior that you want, but it requires an explicit lock object and as such it does not work with the embedded Java object monitor - I do not believe that there is an equivalent to tryLock() for Java object monitors.

Upvotes: 5

Related Questions