Parallel Programming (1)-Sum.msic.Unsafe

Source: Internet
Author: User

Believe that read the Java source of the classmate, Sum.msic.Unsafe this class is not unfamiliar, especially in the Java.util.concurrent package has a lot of use.


Sum.msic.Unsafe Source: http://www.docjar.com/html/api/sun/misc/Unsafe.java.html

Javadoc:http://www.docjar.com/docs/api/sun/misc/unsafe.html


Sum.msic.Unsafe is a low-level (atomic operation at the hardware level), the method of unsafe operation is combined, because Java cannot access to the system bottom, so we can see that the Sum.msic.Unsafe class is mostly native local methods, although the method of the class is Pulblic, However, we cannot invoke unsafe in programming (which can be called arbitrarily in the JDK), and the class can only use its instance in the code that is being trusted.


the next CAs (Compare and swap) are introduced, and the literal understanding is to compare and exchange. CAS contains three operation values: memory address, new value, expected original value. If the value in the memory address is the same as the expected value, then the new value will be replaced, otherwise no action will be made. There are a number of compareandswap*** methods in the Sum.msic.Unsafe class, such as: Compareandswapint,compareandswaplong, Compareandswapobject and so on.

Atomicboolean class, Unsafe object initialization://Setup to use Unsafe.compareandswapint for updatesprivate static final unsafe unsafe = unsafe . Getunsafe ();

To obtain an unsafe instance static method:

public static Unsafe Getunsafe () {      Class cc = Sun.reflect.Reflection.getCallerClass (2);      if (cc.getclassloader () = null)            throw new SecurityException ("Unsafe");      return theunsafe; }

and then a brief introduction to sum.msic.unsafe ":
Extended memory public native long reallocatememory (long address, long bytes);//allocating memory public native long allocatememory (long bytes) ;//release memory public native void Freememory (long address);//Set value in a given memory block public native void Setmemory (Object o, long offset, long b Ytes, byte value);//Copy from one memory block to another memory block public native void CopyMemory (object srcbase, Long Srcoffset, Object destbase, long des Toffset, long bytes);//Gets the value, regardless of the Java access limit, the other has a similar getdouble,getlong,getchar and so on public native object GetObject (object o, Long offset);//Set value, regardless of Java access restrictions, others have similar putdouble,putlong,putchar, etc. public native void PutObject (Object o, long offset);// Gets the local pointer from a given memory address, if not the Allocatememory method, the result will not be determined public native long getaddress (long address);//Store a local pointer to a given memory address, If the address is not the Allocatememory method, the result will not be determined public native void putaddress (long address, long x);//The method returns the memory address offset for the given field, This value is unique for a given filed and is a fixed public native long staticfieldoffset (field F);//reports the location of a given field, whether the field is private,public or protected type, Use public native long objectfieldoffset (field F) with staticfieldbase;//Gets the bit of a given fieldPlace public native Object staticfieldbase (field F);//Ensure that a given class is initialized, which often requires a static domain (field) public native void that combines the base class Ensureclassinitialized (class C);//Can get the offset address of the first element of the array public native int arraybaseoffset (class arrayclass);//can get the conversion factor of an array , which is the incremental address of the elements in the array. Using Arraybaseoffset with Arrayindexscale, you can locate the location of each element in the array in memory, public native int Arrayindexscale (Class arrayclass);// Gets the number of pages of native memory, which is always 2 power-party public native int pageSize ();//tells the virtual machine to define a class without security checks, and by default the class loader and the protection domain are the caller class public native class DefineClass (String name, byte[] B, int off, int len, ClassLoader loader, protectiondomain protectiondomain);//define a class, but do not let it Know the class loader and system dictionary public native class Defineanonymousclass (class Hostclass, byte[] data, object[] cppatches);//Lock object, Must be public native void Monitorenter (object o) that is not locked;//Unlock object public native void Monitorexit (object o);//Attempt to lock object, Returns TRUE or False if the lock is successful and must be unlocked with Monitorexit public native Boolean trymonitorenter (Object o);//throws an exception without notifying public native void ThrowException (Throwable ee);//cas, similar COMPAREANDSWAPINT,COMPAREANDSWAPLONG,COMPAREANDSWAPBOolean,compareandswapchar and so on. Public Final Native Boolean Compareandswapobject (object o, long offset, object expected, object x);//This method gets an offset offset address pair in the object The value of the integer field that is expected to support volatile load semantics. A similar method has getintvolatile,getbooleanvolatile and so on public native object Getobjectvolatile (object o, long offset); When the thread calls the method, the thread will block until it times out, or the interrupt condition appears. Public native Void Park (Boolean isabsolute, long time);//terminating a suspended thread, Return to normal. The Java.util.concurrent package is implemented in the Locksupport class, and it is the use of these two methods, the subsequent will be Java.util.concurrent package related source analysis sorted out. public native void Unpark (Object thread);//Get system load on different time systems public native int getloadaverage (double[] loadavg, int nelems );//Create an instance of a class without calling its constructors, first-order code, various JVM security checks, and other underlying things. Even if the constructor is private, we can create an instance of it through this method, which is a nightmare for singleton mode, haha public native Object allocateinstance (Class cls) throws Instantiationexception;

The Sum.msic.Unsafe class has a private instance: Theunsafe

Private static final unsafe Theunsafe = new unsafe ();
We can get the unsafe instance through the reflection mechanism, here is a simple example:
public class Unsafetest {private static Unsafe unsafe;public static void Main (string[] args) throws Exception {try {//through reflection Gets the Unsafe class field field = Unsafe.class.getDeclaredField ("Theunsafe") under Rt.jar, Field.setaccessible (true), unsafe = ( Unsafe) field.get (null); The attributes of the Integer target = 12;//compareandswapint method are: Target object instance, target object property offset, current expected value, value to be set.// The Compareandswapint method is to modify the value of the object by reflection, modifying the value below the object, which can be offset by the offset of the object field, which can be obtained by Objectfieldoffset System.out.println ( Unsafe.compareandswapint (Target, 12, 11, 10)); SYSTEM.OUT.PRINTLN (target);} catch (Exception e) {System.out.println ("Get Unsafe instance occur error" + e);}}}

Run the above code to set up eclipse:
The windows->preferences->java-complicer->errors/warnings->deprecated and restricted API, in the forbidden References (access rules) is set to warning, which can be compiled through.


Finally: Unsafe classes can cause the JVM to crash because there is no security guarantee, a slight negligence or improper use.


Follow-up will be collated java.util.concurrent package related to the source code analysis, for unsafe each method of detailed application, will be specific analysis.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Parallel Programming (1)-Sum.msic.Unsafe

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.