G
G
gleendo2017-03-05 08:03:04
Java
gleendo, 2017-03-05 08:03:04

What is the difference between a synchronized method and synchronization by object, as well as by class?

In general, the essence of the question is in the title. Please tell me the difference between them. When to use one method or the other. In what ways is one way better than the other and vice versa?

public synchronized void method() {

}

public void method() {
    synchronized (object) {

    }
}

class C {
    public void method() {
        synchronized (C.class) {

        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2017-03-05
@zagayevskiy

There are two types of synchronized method - static and non-static. Static is equivalent to synchronizing the body of a method on a class:

public synchronized static void method() {
}
class C {
    public static void method() {
        synchronized (C.class) {

        }
    }
}

The second is equivalent to synchronizing the method body on this :
public synchronized void method() {
}

public void method() {
    synchronized (this) {
    }
}

The differences seem to be obvious - when synchronizing on an object, you can choose the same object on which to synchronize. Plus, you can choose which piece of code to synchronize - and it must be minimized to speed up.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question