Java keywords synchronized

Source: Internet
Author: User
Tags java keywords

Java keywords synchronized

The synchronized keyword indicates that this method is locked. It is equivalent to checking whether thread A is using thread B (or C D) every time it runs to this method ), if yes, wait until thread B (or C D) that is using this method runs this method and then run thread A. If no, directly run this method in two ways: synchronized Method and synchronized block.

1. synchronized Method:

The synchronized method is declared by adding the synchronized keyword to the method declaration. For example:

Public synchronized void accessVal (int newVal );

The synchronized method controls access to class member variables: each class instance corresponds to a lock, and each synchronized method must obtain the lock of the class instance that calls the method before execution, otherwise the thread is blocked, once the method is executed, the lock is exclusive until the lock is released when the method is returned. Then, the blocked thread can obtain the lock and re-enter the executable status. This mechanism ensures that, at the same time, only one of all the member functions declared as synchronized is in the executable state (because at most only one member function can obtain the lock corresponding to this type of instance ), this effectively avoids access conflicts between class member variables (as long as all methods that may be used to invoke class member variables are declared as synchronized ).

In Java, not only are class instances, but each class also corresponds to a lock. In this way, we can declare the static member function of the class as synchronized, to control its access to static member variables of the class.

Synchronized: if a large method is declared as synchronized, the efficiency will be greatly affected. Typically, if you declare the thread-class method run () as synchronized, since the thread is always running throughout its life cycle, it will never succeed in calling any synchronized Method of this class. Of course, we can put the code of the member variable of the category class into a special method, declare it as synchronized, and call it in the main method to solve this problem, but Java provides us with a better solution, that is, the synchronized block.

 

2. synchronized block:

Use the synchronized keyword to declare the synchronized block. Syntax:

Synchronized (syncObject ){

// Code that allows access control

}

The synchronized block is a code block in which the Code must obtain the lock of the object syncObject (as described earlier, it can be a class instance or class) before execution. The specific mechanism is described earlier. It is highly flexible because it can target any code block and can specify any locked object.

 

 

Some Understanding of synchronized (this)

1. When two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread finishes executing this code block before executing this code block.

2. When a thread accesses a synchronized (this) synchronization code block of the object, access by other threads to all other synchronized (this) synchronization code blocks of the object will be blocked.

3. However, when a thread accesses a synchronized (this) synchronization code block of an object, the other thread can still access parts of the object except the synchronized (this) synchronization code block.

4. The third example also applies to other synchronous code blocks. That is to say, when a thread accesses a synchronized (this) synchronization code block of an object, it obtains the object lock of this object. As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked.

5. The above rules apply to other Object locks.

 

 

A simple example of synchronized

Public class TextThread
{

/**
* @ Param args
*/
Public static void main (String [] args)
{
// TODO automatically generates method stubs
TxtThread tt = new TxtThread ();
New Thread (tt). start ();
New Thread (tt). start ();
New Thread (tt). start ();
New Thread (tt). start ();
}
}

Class TxtThread implements Runnable
{
Int num = 100;
String str = new String ();
Public void run ()
{
While (true)
{
Synchronized (str)
{
If (num> 0)
{
Try
{
Thread. sleep (10 );
}
Catch (Exception e)
{
E. getMessage ();
}
System. out. println (Thread. currentThread (). getName () + "this is" + num --);
}
}
}
}
}

In the above example, Thread. sleep (10) is used to create a time difference, that is, the chance of an error)

Java's multi-thread support and synchronization mechanism are favored by everyone. It seems that using the synchronized keyword can easily solve the problem of multi-thread shared data synchronization. What exactly? -You must have an in-depth understanding of the role of the synchronized keyword.

In general, the synchronized keyword can be used as the modifier of the function or as the statement in the function, that is, the synchronization method and synchronization statement block. If further classification is performed, synchronized can act on instance variables, object reference, static functions, and class literals (literal constants of class names.

Before proceeding, we need to clarify the following points:

A. no matter whether the synchronized keyword is added to the method or object, the lock it acquires is an object, instead of using a piece of code or function as a lock-and the synchronization method is likely to be accessed by objects in other threads.

B. Each object has only one lock associated with it.

C. Implementing synchronization requires a large amount of system overhead as a cost, and may even cause deadlocks. Avoid unnecessary synchronization control as much as possible.

Next we will discuss the impact of synchronized on code in different places:

 

Assume that P1 and P2 are different objects of the same class. This class defines synchronization blocks or Synchronization Methods in the following situations, and P1 and P2 can call them.

 

1. When synchronized is used as a function modifier, the sample code is as follows:

Public synchronized void methodAAA ()

{

//....

}

This is the synchronization method. Which object is synchronized locked at this time? The lock is to call this synchronization method object. That is to say, when an object P1 executes this synchronization method in different threads, they are mutually exclusive to achieve synchronization. However, the other object P2 generated by the Class to which this object belongs can call the method with the synchronized keyword.

The above sample code is equivalent to the following code:

Public void methodAAA ()

{

Synchronized (this) // (1)

{

//.....

}

}

(1) What does this mean? It refers to the object that calls this method, such as P1. It can be seen that the synchronization method essentially acts on the object reference. -- The thread that obtains the P1 object lock can call the synchronization method of P1. For P2, the P1 lock has nothing to do with it, in this case, the program may also get rid of the control of the synchronization mechanism, resulting in data confusion :(

2. Synchronization block. The sample code is as follows:

Public void method3 (SomeObject so)

{

Synchronized (so)

{
//.....
}

}

In this case, the lock is the so object. Whoever gets the lock can run the code it controls. When a specific object is used as the lock, you can write the program in this way, but when there is no clear object as the lock, just want to synchronize a piece of code, you can create a special instance variable (which must be an object) to act as a lock:

Class Foo implements Runnable

{

Private byte [] lock = new byte [0]; // special instance variable

Public void methodA ()
{

Synchronized (lock ){//... }

}

//.....

}

Note: creating a zero-Length byte array object is more economical than any other object-view the compiled bytecode: only three operation codes are required for generating a zero-Length byte [] object, object lock = new Object () requires seven lines of operation code.

3. apply synchronized to the static function. The sample code is as follows:

Class Foo
{

Public synchronized static void methodAAA () // synchronized static function
{
//....
}

Public void methodBBB ()
{

Synchronized (Foo. class) // class literal (class Name literal constant)

}
}

The methodBBB () method in the Code uses class literal as the lock. It produces the same effect as the synchronized static function, and the obtained lock is very special, is the Class of the object currently calling this method (Class, instead of a specific object generated by this Class ).

I remember that I saw in objective Java that using Foo. class and P1.getClass () for synchronization locks is not the same. P1.getClass () cannot be used to lock this Class. P1 refers to the object generated by the Foo class.

It can be inferred that if A class defines A static function A of synchronized, it also defines the instance function B of synchronized, when the same object Obj of this class accesses Methods A and B in multiple threads, the synchronization is not formed because their locks are different. The lock of method A is the object Obj, and the lock of Method B is the Class to which Obj belongs.

 

Summary:

Figuring out which object synchronized is locked can help us design safer multi-threaded programs.

 

There are also some tips to make our synchronized access to shared resources more secure:

1. Define the private instance variable + its get method, instead of the public/protected instance variable. If a variable is defined as public, the object can directly obtain it and change it by bypassing the control of the synchronization method. This is also one of the standard implementations of JavaBean.

2. if the instance variable is an object, such as an array or an ArrayList, the above method is still insecure, because after the External Object obtains the reference of this instance object through the get method, and direct it to another object, so this private variable also changes, it is not very dangerous. At this time, you need to add the get method and synchronized synchronization, and only return the clone () of this private object-in this way, the caller obtains the reference of the object copy.

 

 

Also, the commonly used ones are: Collections. synchronizedMap (new HashMap (), of course, this MAP is the global variable of life in the class, a thread-safe HashMap, and the web application is shared by all web containers, therefore, thread security should be used to ensure data correctness.


How to Use the synchronized keyword in Java?

In my understanding
Sychronized is used to prevent more than two threads from simultaneously accessing the same resource during concurrency. The parameters are used for identification. For example, in the first case: When a function sychronized (object A) and B function sychronized (object B) Call function, other threads can no longer access function a, but can access function B. The second case: When a function sychronized (object A) and B function sychronized (Object A) Call function a in a thread, other functions cannot access function, and cannot access function B.
Please correct me.

What are the characteristics of the synchronized modifier for java? What is the role of the keyword synchronized?

The synchronized keyword of Java. When it is used to modify a method or a code block, it can ensure that at most one thread can execute the code segment at the same time.
1. When two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread finishes executing this code block before executing this code block.

2. However, when a thread accesses a synchronized (this) synchronization code block of the object, the other thread can still access the non-synchronized (this) synchronization code block of the object.

3. When a thread accesses a synchronized (this) synchronization code block of the object, other threads perform synchronization on all other synchronized (this) access to the synchronization code block will be blocked.

4. The third example also applies to other synchronous code blocks. That is to say, when a thread accesses a synchronized (this) synchronization code block of an object, it obtains the object lock of this object. As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked.

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.