"Java" class lock and Object lock lock synchronized pee __java

Source: Internet
Author: User

Recently encountered multithreading problem, originally only used synchronized method lock, for which the object lock and class lock understanding, but not carefully studied. So go back and check the relevant data for collation.


Basic Knowledge


First the introduction of object lock (also called method Lock) with class lock has those different. Object locks are used in the following to replace method locks.

For an object lock, it is for an object, and it only locks the current object by declaring a flag bit at one of the object's memory locations to identify whether the object owns the lock. A general object lock is a syncronized modification of a non-static member variable, or a syncronized modification of a non-static method. For object locks, different objects are not blocked when accessing the same method that is syncronized modified.

Class locks Lock the entire class, and when multiple threads declare objects of the class, they are blocked until the object owning the class lock is destroyed or the class lock is actively released. At this time the blocked thread is singled out for a possession of the class lock, declaring the object of the class. Other threads continue to be blocked.

Whether it is a class lock or an object lock, blocking between the parent class and the subclass is not directly related. When a class lock is added to a parent class, the subclass is unaffected, and vice versa. Because the Synchronized keyword is not part of the method signature, it is decorated with the method. The synchronized modifier is not automatically inherited when the subclass repeats the synchronization method in the parent class or the synchronization method declared in the interface, so the corresponding blocking problem does not occur.

Note: The blocking problem here is that it should be blocked under normal circumstances, and because synchronized is not transitive between the parent class and the subclass, it will not block. What is normally blocked is that, the following will be described in detail. However, when a subclass does not overwrite a method of the parent class, accessing the method through the subclass can cause blocking.

Insert a sentence: The construction method cannot be really synchronized (although you can use a synchronized block in the constructor).

The screenshot below shows how to declare an object lock and how to declare a class lock:

Code Test


As the following code, I declare a class runtest, which contains a Nosyn method, an object lock method Outmethod and a class lock method plus. Declares a class obj that inherits thread thread, which is used to access runtest methods in the class, simulating various test scenarios. The startup test class is Mutithread, in which there are two test methods, one that declares the same test class object and opens multiple threads to test the object lock; the other is to test class locks whenever a new thread is declared and a new test class object is declared.

The specific testing process is divided into two steps. The first step is to run the following code directly, the test results are used to test the lock effect of the object lock, and the second step is to comment out the first two lines of code in the For loop, delete the comments from the remaining three lines of annotated code, and then delete the annotation in the last line of the class obj annotation to test the effect of the class lock.

public class Mutithread {public static void main (string[] args) {runtest runtest = new Runtest ();
			
for (int i = 0; i < i++) {thread thread = new OBJ (runtest, I);//1 the same RunTest1 object but each time there is a new thread thread.start (); Runtest rruntest = new Runtest ();
2 loops each time declares a new object//thread thread = new OBJ (rruntest, i);
		Thread.Start ();
	Class Obj extends Thread {runtest R;

	int i = 0;
		Public OBJ (runtest r, int i) {THIS.R = R;
	THIS.I = i;
       public void Run () {R.nosyn (This.getid ()); Used to test that the same object accesses different methods in different threads if (i% 2 = 0) {r.outmethod2 ();//Object Lock Method 2}else{R.outmethod ();//Object Lock Method 1}// Runtest.plus ();
	Class Lock Method} class Runtest {static int i = 0;
	public void Nosyn (long threadId) {System.out.println ("Nosyn:class obj->" + This + ", threadid->" + threadId);
		Synchronized public void Outmethod () {System.out.println (' in Outmethod begin ');
		try {thread.sleep (2000L);
	catch (Interruptedexception e) {}	System.out.println ("In the Outmethod End");
		Synchronized public void OutMethod2 () {System.out.println (' in OUTMETHOD2 begin ');
		try {thread.sleep (2000L);
	catch (Interruptedexception e) {} System.out.println ("In OutMethod2 End");
			public static void Plus () {synchronized (Runtest.class) {System.out.println ("Start:" + i);
			try {thread.sleep (3000L);
			catch (Interruptedexception e) {} i++;
		System.out.println ("I is" + i);
 }
	}
}
Execution ResultsAccording to the above test steps, the test results for class locks are as follows:
The first part output: Nosyn:class obj->test. RUNTEST@3851DDD2, threadid->10
In OUTMETHOD2 begin
Nosyn:class Obj->test. RUNTEST@1722FE15, threadid->13
In Outmethod begin
Nosyn:class Obj->test. RUNTEST@6E1B0CAF, threadid->15
Nosyn:class Obj->test. Runtest@31ddeda2, threadid->16
In OUTMETHOD2 begin
Nosyn:class Obj->test. RUNTEST@5BE9D36, threadid->14
In OUTMETHOD2 begin
In Outmethod begin
Nosyn:class Obj->test. RUNTEST@1624BEF5, threadid->11
In Outmethod begin
Nosyn:class Obj->test. Runtest@1f92ee25, threadid->18
In OUTMETHOD2 begin
Nosyn:class Obj->test. RUNTEST@2543472C, threadid->17
In Outmethod begin
Nosyn:class Obj->test. RUNTEST@6750CF54, threadid->19
In Outmethod begin
Nosyn:class Obj->test. RUNTEST@8AFCD0C, threadid->12
In OUTMETHOD2 begin/************************** The above output is almost simultaneously *********/the second part output: in the outMethod2 end
In Outmethod end
In Outmethod end
In OutMethod2 end
In Outmethod end
In Outmethod end
In OutMethod2 end
In Outmethod end
In OutMethod2 end
In the outMethod2 end/**************************sleep some time *********/
Part III output
start:0
I is 1
Start:1
I is 2
Start:2
I is 3
Start:3
I is 4
Start:4
I is 5
Start:5
I is 6
Start:6
I is 7
Start:7
I is 8
Start:8
I is 9
Start:9
I
is


Following the execution of the code, this explains why code execution causes blocking:

1: It will first execute the unlocked method, whether it is an object multiple threads or an object in each thread, no lock method has no effect. For object locks and class locks, only the locking method has a different effect.

2: When multiple objects to the same object lock method calls will be blocked, and different objects to different methods of access will not be blocked, even if the object lock added. When the same object accesses a method in thread 1, then another lock method is accessed in thread 2, which is also blocked. For the above code, the object Runtest in thread 1 accesses the Outmethod, while the Access OUTMETHOD2 on thread 2 is blocked.

3: For class locks, the entire class is locked, and it is said that only one object has the current class lock. When an object has a class lock, another object will be blocked if it wants to compete for the lock. Two object a,b, B is inaccessible if a is accessing a method function that is decorated by a class lock. Because class locks can only be owned by an object at the same time. Relative to the object lock, it is different. Or A,b two objects, if a is accessing the function that the object lock modifies, then B can also be accessed at the same time.

For the analysis of the output of the class lock, its output is expressed in three parts:

In the first part of the output is almost simultaneous output, because each thread is a new object, different object Access object lock will not be blocked, so almost according to the sequence of the program output;

The second part of the output is two methods of sleep time consumption, there is no problem;

The third part is to calculate the i++, then output the result, this part of the output is relatively slow. Because the plus method is a class lock, at the same time only one object owns the lock, so multiple threads must sequentially execute the result, so the output of the last I is also 10.

For object locks, when an object has a lock, it accesses a method with an object lock, and the method calls another method of object locking in the class, which is not blocked at this time. This is implemented by Java through a reentrant lock mechanism. A reentrant lock means that the lock can be acquired repeatedly after an object has an object lock. Because the synchronized block is reentrant, when you access an object lock method, continuing access to other object locks in the method is not blocked.


Another more detailed example: http://ifeve.com/who-is-lock/

One answer on the StackOverflow: Http://stackoverflow.com/questions/3047564/java-synchronized-method-lock-on-object-or-method

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.