2

Java synchronized statement is a way of protecting a data resource from being access simultaneously by multiple threads. It can be done via doing synchronize to an object X as a critical section or mutex.

class MyClass
{
    int a;
    object X = new object();

    void Foo()
    {
        synchronized(X)
        {
            a++;
        }
    }
}

Is there any way of doing try-lock to X instead of lock like this?

void Foo()
{
    if(try_synchronized(X)==true)
    {
        a++;
    }
}

Unfortunately, this Q&A say that ReentrantLock is the alternative way, but synchronized keyword is implemented under Java VM, so this question is different.

Community
  • 1
  • 1
Hyunjik Bae
  • 2,721
  • 2
  • 22
  • 32
  • Mentioned the difference. – Hyunjik Bae Feb 23 '15 at 03:57
  • 1
    What it's saying is that you can't do such a thing with `synchronized`. The solution is with the `java.util.concurrent` types. – Sotirios Delimanolis Feb 23 '15 at 05:31
  • I don't know that I've ever seen an application program use `lock.tryLock()` or anything like it. I don't think its a smart thing to do. If a thread needs to test a lock, that probably means the thread is responsible for more than one thing. That's bad design. Instead of one thread with N responsibilities, it would be better to have N threads, each with one responsibility. – Solomon Slow Feb 23 '15 at 14:58
  • There are uses of `lock.tryLock()`. See for example the [javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.ManagedBlocker.html) of `ManagedBlocker`. – Rémi.B Apr 10 '19 at 15:40

0 Answers0