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

concurrency, java, multithreading

Solution

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();

Problem

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 } } } ```

Original source