The nature of synchronize lies in the member functions of the class and the Java reflection mechanism.

Source: Internet
Author: User

 1. Understanding about object classes

As we all know, object is the base class of all Java classes, meaning that all Java classes inherit the 11 methods of the object. We recommend that you check the source code of the 11 member functions of the object to see the default implementation method. For example, in the equals method, the default implementation is to use "=" to compare, that is, to directly compare the memory address, return true or false. The tostring () method returns the string composition method ??

"Getclass (). getname () +" @ "+ integer. tohexstring (hashcode ())"

In fact, you can understand the composition of this string without having to explain it too much. Next let's take a look at hashcode ():

Public native int hashcode ();

Because the native method is related to the OS processing method, there is only one declaration in the source code. If we are interested, we can fully explore how its hashcode is generated by the OS? However, I suggest that you remember to use the principles first! First, if the equals () method has the same hashcode for the same object, but the equals () object is not the same, it is not guaranteed that the hashcode () method returns different integers. In addition, when you run the same program next time, the same object may not be the original hashcode.

What about other methods? Nofigy (), policyall (), clone (), and wait () are all native methods, which indicate that they depend on the implementation of the operating system. The last interesting method is finalize (). Similar to the C ++ destructor, the signature is protected, which proves that the method can be used only after the inheritance extension, and the method body is empty, do nothing. It serves to notify the JVM that the object is no longer used and can be destroyed at any time. The actual destruction right lies in the virtual machine. So does it really do nothing? Not necessarily, in fact, if it is a thread object, it will lead to a higher priority of the thread within a certain range, leading to faster destruction to save memory and improve performance. In fact, from a common sense, we can guess this way.
JVM practice.

2. Relationship between heavy load hashcode () and collection framework

I once heard from a senior who has been engaged in Java training for many years that in his opinion the hashcode method has no significance, just to prove that the same hashcode will lead to equal equals methods. Even some predecessors have made such a mistake, which means it is easy to be ignored. So what is the purpose of the hashcode () method?

After learning the Data Structure Course, You will know that there is a structure called hash table, which aims to improve the query efficiency by assigning a unique index to each object. Therefore, Java will not modify this concept at will, so the only function of hashcode is to support the hash table structure in the data structure. In other words, that is, the hashcode () method must be reloaded only when hashtable, hashmap, and hashset of the Collection framework are used,

In this way, we can control whether the indexes in the hash structure are equal. Here is an example:

In order to write a solution program, we need to randomly list different permutation and combinations composed of 1, 2, 3, and 4. Therefore, I wrote an array class to store the combination result with int, then, we add the randomly generated combination to a hashset, which is to take advantage of the characteristics that hashset does not include repeated elements. But how does a hashset determine whether it is a repeated element? The result returned by hashcode () is equal. You can perform this experiment:

Int [] A = {1, 2, 4 };

Int [] B = {1, 2, 4 };

System. Out. println (A. hashcode ());

System. Out. println (B. hashcode ());

 

This is clearly the same combination, but it is different hashcode. When you add a set, it will be treated as different objects. At this time, we need to rewrite the hashcode () method by ourselves. How can we write it? Actually, it is based on the original hashcode (). After all, it is the implementation of the operating system. There are many implementation methods to find the unique identifier of the same object. The implementation method is as follows:

First, override the tostring () method:

Return a [0] "+" a [1] "+" a [2] "+" a [3]; // intuitive display

Then use tostring () to calculate hashcode ():

Return this. tostring (). hashcode ();

In this way, both A and B will return "1234" in the test tostring (). hashcode (), because the string copies in the memory are the same, "1234 ". hashcode () must return the same result.

Speaking of this, I believe everyone can understand it better than me. Do not misunderstand the role of the hashcode () method in the future.

3. About the member functions of the class and the Java reflection mechanism

I have been familiar with Java for a long time and have heard many teachers talk about the dynamic runtime mechanism and reflection mechanism of Java. Indeed, they are all notable features of Java. I have introduced them in the first article during runtime loading. Now I want to talk about the reflection mechanism. In Java, the class and method class in the Java. lang package are used to implement the memory reflection mechanism.

People familiar with C ++ must know that the following cannot be done in C ++: When a class name is passed as a string parameter during runtime, all information of this class can be obtained, including all its methods and detailed information about the methods. You can also instantiate an object and call any method of the object by finding the method name. This is because the Java class in the memory contains a description of the class itself in addition to the static dynamic data zone in c ++, and through the information in this description, in order to help us read the content and get all the information of the target class, so as to implement the reflection mechanism. Have you ever thought about how to know the attributes of a JavaBean instance when we need it? Another simple example is to write one by yourself.
An Parser:

A. Get the class object through class. forname ("Bean class name"), for example, abeanclass

B. Use the getmethods () method of abeanclass to obtain the method [] Object

C. According to the specification, all the words after the get method name represent an attribute of the bean.

D. if you already know a method name, you can call newinstance () to obtain an instance, and then pass the method name and parameters required by the method through the invoke () method, you can call this method dynamically.

Of course, there are more complex applications. We will not go into details here. You can refer to the class and method class methods.

4. Acknowledge the nature of synchronize

Synchronize everyone knows that synchronize means synchronization and locking. In fact, its nature is far less complex than everyone thinks. When the synchronize method is called, the lock actually loads the object. Of course, if it is a static class, the lock is applied to the class, and the call stop lock is released. Its implementation principle is very simple, just to prevent the second lock from being added to the same object or class again, that's all. A simple example is enough to illustrate the problem:

Class {

Synchronized void F (){}

Void g (){}

}

 

When an object A of A is called by the first thread for its F () method, the second thread cannot call the Synchronized Method of A, for example, F (), because it is trying to add a second lock to the object. However, calling g () is acceptable, because it is not produced by adding two locks to the same object.

So that everyone can understand? Understanding its principles can help you better design synchronization mechanisms and avoid misuse of locks.

Related Article

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.