JavaRush /Java Blog /Random EN /Thread Synchronization, Object Locking, and Class Locking...
CynepHy6
Level 34
Великий Новгород

Thread Synchronization, Object Locking, and Class Locking

Published in the Random EN group
Thread synchronization, object locking and class locking - 1Synchronization refers to multithreading. A synchronized block of code can only be executed by one thread at a time. Java supports multiple threads for execution. This could result in two or more threads accessing the same field or object. Synchronization is a process that allows all parallel threads in a program to run synchronously. Synchronization avoids memory consistency errors caused by inconsistent access to shared memory. When a method is declared as synchronized, the thread holds a monitor for the object whose method is being executed. If another thread is executing a synchronized method, your thread will block until the other thread releases the monitor. Synchronization is achieved in Java using a reserved word synchronized. You can use it in your classes by defining synchronized methods or blocks. You won't be able to use synchronizedin variables or attributes in a class definition.

Object-level locking

This is a mechanism for synchronizing a non-static method or non-static block of code such that only one thread can execute a given block or method on a given instance of a class. This should be done whenever you need to make instance-level data thread safe. Example:
public class DemoClass{
    public synchronized void demoMethod(){}
}
or
public class DemoClass{
    public void demoMethod(){
        synchronized (this)        {
            //other thread safe code
        }
    }
}
or
public class DemoClass{
    private final Object lock = new Object();
    public void demoMethod(){
        synchronized (lock)        {
            //other thread safe code
        }
    }
}

Class-level locking

Prevents multiple threads from entering a synchronized block during execution in any of the available instances of the class. This means that if there are 100 instances of the class during program execution DemoClass, then only one thread at that time will be able to execute demoMethod()in any of the cases, and all other cases will be blocked for other threads. This is necessary when you need to make static data thread safe.
public class DemoClass{
    public synchronized static void demoMethod(){}
}
or
public class DemoClass{
    public void demoMethod(){
        synchronized (DemoClass.class)        {
            //other thread safe code
        }
    }
}
or
public class DemoClass
{
    private final static Object lock = new Object();
    public void demoMethod(){
        synchronized (lock)        {
            //other thread safe code
        }
    }
}

Some Important Notes

  1. Synchronization in Java ensures that no two threads can execute a synchronized method at the same time or in parallel.

  2. synchronizedcan only be used with methods and code blocks. These methods or blocks can be static or non-static.

  3. Whenever any thread enters a synchronized method or block it acquires a lock and whenever a thread exits a synchronized method or block the JVM releases the lock. The lock is released even if the thread leaves the synchronized method after completion due to any errors or exceptions.

  4. synchronizedin Java , this means that if a synchronized method calls another synchronized method that requires the same lock, the current thread that holds the lock can enter that method without acquiring the lock.

  5. Synchronization in Java will fail NullPointerExceptionif the object used in the synchronized block is null. For example, in the code example above, if the lock is initialized as null, the synchronized (lock) will throw NullPointerException.

  6. Синхронизированные методы в Java вносят дополнительные затраты на производительность вашего applications. Так что используйте синхронизацию, когда она абсолютно необходима. Кроме того, рассмотрите вопрос об использовании синхронизированных блоков codeа для синхронизации только критических секций codeа.

  7. Вполне возможно, что и статический и не статический синхронизированные методы могут работать одновременно or параллельно, потому что они захватывают замок на другой an object.

  8. В соответствии со спецификацией языка вы не можете использовать synchronized в конструкторе это приведет к ошибке компиляции.

  9. Не синхронизируйте по не финальному (no final) полю, потому что link, на не финальное поле может измениться в любое время, а затем другой поток может получить синхронизацию на разных an objectх и уже не будет ниHowой синхронизации вообще. Лучше всего использовать класс String, который уже неизменяемый и финальный.

Удачи в обучении!! Оригинал: Object level lock vs Class level lock in Java
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION