Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an acceptable way to create a lock in Java ? [closed]

I ran into this logic that someone had implemented at work today and it just feels wrong to be creating locks this way. Do you guys have a better solution for this ? The problem with not using synchronized block on myObj is that it can be null. Any other suggestions ??

 public class myClass {
    private Object myObj;
    private Object lock = new Object();

    public void method1() {
        synchronized( lock ) {
            // has logic to read myObj
        }
    }


    public void method2()  {
        synchronized( lock ) {
            // has logic to update myObj
        }
    }
}
like image 728
user3019108 Avatar asked Nov 21 '13 19:11

user3019108


People also ask

What does lock lock (); do in java?

The lock() method is one of the most important methods of the Lock interface. It is used for acquiring the lock. For thread scheduling purposes, the current thread becomes disabled when the lock is not available. The lock() method is a public method that returns void.

How many types of locks are there in java?

The tool needed to prevent these errors is synchronization. In synchronization, there are two types of locks on threads: Object-level lock: Every object in java has a unique lock.


2 Answers

Looks appropriate to me. I'd also add final to the lock declaration to make sure it doesn't inadvertently get changed:

private final Object lock = new Object();
like image 175
Tudor Avatar answered Sep 18 '22 20:09

Tudor


It's appropriate. Another way, while it is hotly debated whether it is proper, is to synchronize this if you want to lock.

like image 28
Rogue Avatar answered Sep 19 '22 20:09

Rogue