Synchronized in Java

Source: Internet
Author: User

The concept of lock is familiar to everyone, when a thread A has already held a lock when thread B tries to enter a code segment protected by this lock. It will be blocked. The operation granularity of the lock is "thread", not the call. Each Java object can be used as a mutex (synchronized) that implements synchronization, which is called a built-in lock. When a thread enters a synchronous code block or method, it automatically obtains the built-in lock, and automatically releases the built-in lock when exiting the synchronization code block or method. Entering a synchronous code block or synchronization method is the only way to get a built-in lock.

The use of synchronized is essentially the following three types

    • For synchronous methods, the lock is the current instance object.
    • For a static synchronization method, the lock is the class object of the current object.
    • For synchronous method blocks, the lock is an object configured in synchonized brackets.

There are 5 ways to use the style:

    • On the method of synchronization, divided into (1) instance method/(2) static method, the difference between the two said
    • Synchronization on the internal block is divided into (3) synchronize (This), (4) synchonrize (Xxx.class), (5) synchonrize (mutex)
 Public classSyncmethod {Private intValue = 0; Private FinalObject Mutex =NewObject ();  Public synchronized intincAndGet0 () {return++value; }     Public intIncAndGet1 () {synchronized( This){            return++value; }    }     Public intIncAndGet2 () {synchronized(Syncmethod.class){            return++value; }    }     Public intIncAndGet3 () {synchronized(mutex) {return++value; }    }     Public StaticSynchonrizeintIncAndGet4 () {synchronized(mutex) {return++value; }    }}

As a cosmetic multibyte on a method declaration, synchronized modifies a non-static method to indicate that the heap object that called the method is locked
Modifying a static method means that the class object in the method area is locked X.class
Synchronized (X.class) uses class objects as monitor.
Both synchronized (this) and synchronized (mutexes) are object locks, and at the same time each instance guarantees that only one thread can access the resources in the block.

sychronized objects are best chosen to reference objects that do not change (for example, are marked as final, or are never changed after initialization), although synchronized is locked on the object, but it first uses references to locate the object, which can have unintended consequences if the reference changes. Lock is provided after JDK1.5, so when to use synchronized, when to use lock?
The advantage of Reentrantlock is that it provides programmers with more choices and better extensibility, such as fair lock and non-fairness lock, read-write lock, Countlatch and so on. Lock implements all the functions of the synchronized, while providing more advanced and finer-grained control. For example, Reentrantlock has the following items: Waiting is interruptible, a fair lock is achieved, and a lock can bind multiple conditions. Compared with the previous comparison, the performance of Reentrantlock is synchronized relatively better. With the optimizations of JDK6 and subsequent versions (introducing biased locks, spin locks, lightweight locks, and heavyweight locks), their differences are already very small. At least from the official point of view is more inclined to use synchronized.

Question 1:synchronized will there be a deadlock?

Question 2: Why do synchronized need to bind objects?
The JVM specification specifies that the JVM implements method synchronization and code block synchronization based on entering and exiting the monitor object, but the implementation details are different. Code block synchronization is implemented using Monitorenter and monitorexit directives, and method synchronization is implemented in another way, details are not explained in detail in the JVM specification, but synchronization of methods can also be implemented using these two instructions. The monitorenter instruction is inserted at the beginning of the synchronization code block after compilation, and Monitorexit is inserted at the end of the method and at the exception where the JVM guarantees that each monitorenter must have corresponding monitorexit paired with it. Any object has a monitor associated with it, and when a monitor is held, it is locked. When the thread executes to the monitorenter instruction, it attempts to take ownership of the monitor that corresponds to the object, which is attempting to acquire the lock on the object. So, this is related to the object, which means there must be somewhere in the object that holds the lock state of the current object. In fact, the memory layout of the Java object is as follows: Object header (header), instance (Instance data), and aligned padding (Padding). The object header (header) 64-bit system occupies 16bytes (regardless of JVM compression), Mark Word is used to store the object's own runtime data, such as hash code (HASHCODE), GC generational age, lock status flag, thread-held lock, biased thread ID, biased time stamp, and so on. For example, in a 32-bit hotspot virtual machine where the object is not locked, the 25Bits in Mark Word's 32 bits space is used to store the object hash code (HASHCODE), 4Bits is used to store the object's generational age, and 2Bits is used to store the lock flag bit, 1Bit fixed to 0.

Question 3: What is a Class object?
In fact, in a sense, there are two kinds of objects in Java: Instance objects and Class objects. An instance object is an instance of a class that we normally define, and the class object is not available with the New keyword because it is the information that the JVM generates to hold the corresponding class, in other words, When we have defined a class file and compiled it into a. Class bytecode, the compiler creates a class object for us and saves it in the. class file. The class object is the information that the JVM uses to hold object instance objects, and in addition, we can think of the class object as a generic instance object, in fact all class objects are examples of classes. There are three ways to get the class object corresponding to an instance object:

Class c == Class.forName ("Meihuan"= Meihuan.  Class;

Synchronized in 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.