Object-level Lock vs Class-level lock –java

Source: Internet
Author: User
Tags class definition

Synchronization is for multithreading. Synchronized methods or blocks of code can be executed by only one thread at a time.

Java supports multithreading for execution. This may cause two or more threads to access the same field or object. Synchronization is a process that synchronizes all concurrently executing threads. Synchronization avoids memory consistency errors caused by inconsistent shared memory views. When a method is declared as synchronous, if a thread is executing a synchronous method, the thread holds the monitor for the method object, and the thread is blocked until the thread releases the monitor.

Synchronization is implemented in Java using the Synchronized keyword. You can use the Synchronization keyword for a method or block that you define in a class. The keyword cannot be used with local variables in the class definition.

Object Level Lock

Object-level locking is a mechanism by which only one thread can execute a block of code on a given instance of a class when you want to synchronize a non-static method or a non-static block of code. You should always do this to make instance-level data thread safe. This can be done as follows:

 Public class democlass{    publicsynchronizedvoid  DemoMethod () {}}

Or

 Public class democlass{    publicvoid  DemoMethod () {        synchronized (this)        {            //Otherthread safe code        }}    } 

Or

 Public class democlass{    privatefinalnew  Object ();      Public void DemoMethod () {        synchronized  (lock)        {            //other Thread safe Code        }}    }
class-Level locks

Class-level locking prevents multiple threads from entering a synchronization block in all available instances at run time. This means that if there is a Democlass instance at run time, only one thread can execute DemoMethod () on either instance at the same time, and all other instances will be locked for other threads. This is always done in order to make the static data thread safe.

 Public class democlass{    publicsynchronizedstaticvoid  DemoMethod () {}} 

Or

 Public class democlass{    publicvoid  DemoMethod () {        synchronized (DemoClass . class )        {            //Otherthread safe code        }}    }

Or

 Public class democlass{    privatefinalstaticnew  Object ();      Public void DemoMethod () {        synchronized  (lock)        {            //other Thread safe Code        }}    }
a number of important matters
    1. In Java, to ensure that no two threads can execute a synchronous method at the same time, this requires the same lock.
    2. The Sync keyword can only be used for methods, code blocks, and final fields. These methods or blocks can be either static or non-static.
    3. When a thread enters a Java synchronization method or block, it acquires the lock and releases the lock when it leaves the Java synchronization method or block. The thread completes the synchronization method, or the lock is freed due to any errors or exceptions.
    4. Java synchronization keywords are reentrant, which means that if a Java synchronization method calls another synchronous method that requires the same lock, the current thread holds the lock and can enter directly without acquiring a lock.
    5. If an object that uses a Java synchronization block is empty, Java synchronization will throw nullpointerexception. For example, in the preceding code example, if the lock is initialized to NULL, the synchronization (lock) throws NullPointerException.
    6. Java synchronization consumes your application's performance. So it is absolutely necessary to use synchronization. Also, consider using a synchronous block of code to synchronize key parts of your code.
    7. Both static and non-static synchronization methods may run concurrently or concurrently because they are locked on different objects.
    8. Depending on the Java language Specification, it is illegal to use synchronous keywords on constructors, which can lead to compilation errors.
    9. Do not synchronize non-final fields. Because a reference to a non-final field can change at any time, different threads may synchronize on different objects, which is simply out of sync. It is best to use the string class, which is already immutable and is declared final.

Happy Learning!!

Object-level Lock vs Class-level lock –java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.