Talk about the unsafe class of Java

Source: Internet
Author: User
Tags volatile

Recently looking at Java and contracted the source code, found the magic of unsafe class, carefully studied, here to share with you.

The unsafe class is under the Sun.misc package and is not part of the Java standard. However, many basic Java libraries, including some widely used high-performance development libraries, are based on the unsafe class, such as Netty, Cassandra, Hadoop, Kafka, and so on. The unsafe class plays a significant role in improving the operational efficiency of Java and enhancing the underlying operational capabilities of the Java language.

The unsafe class gives Java the ability to manipulate memory space as a pointer to the C language, as well as a pointer problem. Excessive use of the unsafe class will make the odds of error bigger, so Java officials are not recommended, and official documents are barely available. Oracle is planning to remove the unsafe class from Java 9, which is too big if it really does.

usually we'd better not use the unsafe class unless we have a definite purpose and have a deep understanding of it. There are some more tricky ways to use the unsafe class. The unsafe class uses a singleton pattern, which needs to be obtained by means of a static method Getunsafe (). However, the unsafe class makes a restriction, and if it is a normal invocation, it throws a SecurityException exception, and only classes loaded by the main ClassLoader can call this method. Its source code is as follows:

1  Public StaticUnsafe Getunsafe () {2Class var0 =Reflection.getcallerclass ();3     if(!Vm.issystemdomainloader (Var0.getclassloader ())) {4         Throw NewSecurityException ("Unsafe");5}Else {6         returnTheunsafe;7     }8}

There are also ways to load user code with the main classloader, such as setting the Bootclasspath parameter. But the simpler approach is to use Java reflection, as follows:

1 Field f = Unsafe. class. Getdeclaredfield ("Theunsafe"); 2 f.setaccessible (true); 3 unsafe unsafe = (unsafe) f.get (null);

Once we get to the unsafe instance, we can do whatever we like. The unsafe class provides the following features:

first, memory management . This includes allocating memory, freeing memory, and so on.

This section includes allocatememory (allocating memory), Reallocatememory (reallocating memory), CopyMemory (copy memory), Freememory (freeing memory), getaddress (get memory address), Addresssize, PageSize, getInt (Gets the integer that the memory address points to), Getintvolatile (Gets the integer that the memory address points to, and supports volatile semantics), Putint (writes an integer to the specified memory address), Putintvolatile (writes an integer to a specified memory address and supports volatile semantics), Putorderedint (writes an integer to a specified memory address, an ordered or deferred method), and so on. GetXXX and putxxx contain a variety of basic types of operations.

Using the CopyMemory method, we can implement a generic method of object copying, eliminating the need to implement the Clone method for each object, but this common method can only be used to make shallow copies of objects.

Second, unconventional object instantiation.

The Allocateinstance () method provides another way to create an instance. Usually we can instantiate an object with new or reflection, using the Allocateinstance () method to directly generate an object instance without calling the constructor method and other initialization methods.

This is useful when objects are deserialized and can be rebuilt and set to final fields without the need to call the constructor method.

Third, Operation class, object, variable.

This section includes staticfieldoffset (static domain offset), defineclass (definition Class), Defineanonymousclass (defining anonymous classes), ensureclassinitialized (ensuring class initialization), Objectfieldoffset (object domain offset) and other methods.

With these methods we can get pointers to objects, and by offsetting pointers, we can not only directly modify the data that the pointers point to (even if they are private), we can even find objects that the JVM has identified as garbage and can be recycled.

Four, array operation.

This section includes methods such as Arraybaseoffset (gets the offset address of the first element of the array), Arrayindexscale (Gets the incremental address of the elements in the array), and so on. Arraybaseoffset is used in conjunction with Arrayindexscale to position each element in the array in memory.

Because Java has an array maximum of integer.max_value, a large array can be implemented using the unsafe class's memory allocation method. In fact, such data can be thought of as C arrays, so you need to be aware of freeing up memory at the right time.

five, multi-threaded synchronization. including lock mechanism, CAS operation and so on.

This part includes Monitorenter, Trymonitorenter, Monitorexit, Compareandswapint, Compareandswap and other methods.

Where Monitorenter, Trymonitorenter, monitorexit have been marked as deprecated and are not recommended.

The CAS operation of the unsafe class is probably the most used, and it provides a new solution for the lock mechanism of Java, such as Atomicinteger and other classes are implemented by this method. The Compareandswap method is atomic, which avoids the heavy locking mechanism and increases the efficiency of the Code. This is an optimistic lock, and it is generally assumed that in most cases there is no race condition, and if the operation fails, it is retried until it succeeds.

Vi. suspend and resume.

This part includes the methods of Park, Unpark and so on.

Suspending a thread is implemented through the park method, and after calling park, the thread will block until a condition such as a timeout or interruption occurs. Unpark can terminate a suspended thread and return it to normal. The suspend operation of threads in the entire concurrency framework is encapsulated in the Locksupport class, with various versions of the Pack method in the Locksupport class, but eventually the Unsafe.park () method is called.

Seven, memory barrier.

This part includes the methods of Loadfence, Storefence, fullfence and so on. This is a new introduction in Java 8 that defines memory barriers and avoids code reordering.

Loadfence () indicates that all load operations before the method are completed before the memory barrier. Similarly storefence () indicates that all store operations before the method are completed before the memory barrier. Fullfence () indicates that all load and store operations before the method are completed before the memory barrier.

Talk about the unsafe class of 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.