Java Programming: Unsafe classes

Source: Internet
Author: User

The unsafe class is used in multiple classes of JDK source code, and this class provides some of the more underlying functions that bypass the JVM, and is based on its implementation to improve efficiency. However, it is a double-edged sword: As its name suggests, it is unsafe, and its allocated memory needs to be manually free (not collected by GC). The unsafe class provides a simple alternative to some of the features of JNI: ensuring efficiency while making things easier.

This article is mainly the following articles of the collation, translation.

http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/

1. Most methods of the Unsafe API are native implementations, which consist of 105 methods, consisting mainly of the following categories:

(1) Info related. Primary return some low-level memory information: addresssize (), PageSize ()

(2) Objects related. The main object and its domain manipulation methods are provided: Allocateinstance (), Objectfieldoffset ()

(3) class-related. Mainly provides class and its static domain manipulation method: Staticfieldoffset (), DefineClass (), Defineanonymousclass (), ensureclassinitialized ()

(4) Arrays related. Array manipulation methods: Arraybaseoffset (), Arrayindexscale ()

(5) Synchronization related. Mainly provides low-level synchronization primitives (such as CPU-based CAS (COMPARE-AND-SWAP) primitives): Monitorenter (), Trymonitorenter (), Monitorexit (), Compareandswapint () , Putorderedint ()

(6) Memory related. Direct Memory access method (direct manipulation of local memory bypassing JVM heap): Allocatememory (), CopyMemory (), Freememory (), getaddress (), GetInt (), Putint ()

1  Packagecom.yeepay.sxf.hashmaptest;2 3 ImportJava.lang.reflect.Field;4 5 ImportSun.misc.Unsafe;6 7  Public classTestunsafe {8 9      Public Static voidMain (string[] args)throwsnosuchfieldexception, SecurityException, IllegalArgumentException, Illegalaccessexception, instantiationexception {Ten         //Get Properties OneField F=unsafe.class. Getdeclaredfield ("Theunsafe"); A         // -F.setaccessible (true); -         //Get Instance theUnsafe unsafe= (unsafe) f.get (NULL); -          -         //instantiate a class -Player player= (player) unsafe.allocateinstance (player).class); +         //print Age Printing results: 0 -System.out.println ("Testunsafe.enclosing_method ()" +player.getage ()); +          APlayer.setage (100); at          -         //Printing Results -System.out.println ("Testunsafe.main ()" +player.getage ()); -          -     } -      in } -  to /** + * General Class -  * @authorSXF the  * *  */ $ classplayer{Panax Notoginseng     //Age -     Private intAge=12; the      +     //privatization of constructor functions A     PrivatePlayer () { the          This. age=50; +     } -  $      Public intGetage () { $         returnAge ; -     } -  the      Public voidSetage (intAge ) { -          This. Age =Age ;Wuyi     } the}
View Code

A
Public native long Objectfieldoffset (field field);
==> returns the memory address offset for the specified static field, which in other methods of this class is simply used as an access
A way to ==> a specific field. This value is unique for a given field, and subsequent calls to the method should return the same value

Two
Public native Boolean compareandswapint (Object obj, long offset, int expect, int update);
The ==> compares the long field and the expected value at the offset position of obj, if the same is updated. The operation of this method should be atomic, thus providing a non-disruptive way to update long field. Successful return true, unsuccessful return false
==>obj: Contains the object for which you want to modify field
The offset of the long field in the ==>offset:obj object
==>expect: The value that you want to exist in field
==>update: If the expected expect is the same as the current value of field, set the value of filed to this new value

Three
Public native Boolean Compareandswapobject (object obj, long offset, object expect, object update);
==> compares the object field and the expected value at the offset position of obj, if the same is updated. The operation of this method should be atomic, thus providing a non-disruptive way to update the Object field. Successful return true, False return unsuccessful
==>obj: Contains the object for which you want to modify field
Offset of the object Type field in the ==>offset:obj
==>expect: The value that you want to exist in field
==>update: If the expected expect is the same as the current value of field, set the value of filed to this new value

Four
public native void Putorderedint (Object obj, long offset, int value);
==> sets the value of the integer field in the Obj object that corresponds to the offset shift address to the specified value. This is an ordered or deferred Putintvolatile method, and there is no guarantee that the change in value is immediately visible to other threads. Use only when field is <code>volatile</code> modified and expects to be accidentally modified.
==>obj: Contains the object for which you want to modify field
==>offset: Offset of integer field in <code>obj</code>
==>value:field the new value to be set

Five
public native void Putorderedlong (Object obj, long offset, long value);
==> sets the value of the long field in the Obj object that corresponds to the offset shift address to the specified value. This is an ordered or deferred <code>putLongVolatile</cdoe> method, and there is no guarantee that the change in value is immediately visible to other threads. Use only when field is <code>volatile</code> modified and expects to be accidentally modified.
==>obj: Contains the object that needs to modify field
Offset of long field in ==>offset:<code>obj</code>
==>value:field the new value to be set

Six
public native void Putorderedobject (object obj, long offset, object value);
==> sets the value of the integer field in the Obj object that corresponds to the offset shift address to the specified value. Support for volatile store semantics
==>obj: Contains the object that needs to modify field
Offset of integer field in ==>offset:<code>obj</code>
==>value:field the new value to be set

Seven
public native void Putintvolatile (Object obj, long offset, int value);
==> sets the value of the integer field in the Obj object that corresponds to the offset shift address to the specified value. Support for volatile store semantics
==>obj: Contains the object that needs to modify field
Offset of integer field in ==>offset:<code>obj</code>
==>value:field the new value to be set


Eight
public native int Getintvolatile (Object obj, long offset);
==> gets the value of the integer field in the Obj object that corresponds to the offset shift address, and supports volatile load semantics.
==>obj: The object that contains the field that needs to be read
Offset of integer field in ==>offset:<code>obj</code>

Nine
public native void Putlongvolatile (Object obj, long offset, long value);
==> sets the value of the long field in the Obj object that corresponds to the offset shift address to the specified value.
==>obj: Contains the object that needs to modify field
==>offset: Offset of long field in <code>obj</code>
==>value:field the new value to be set

Ten
Public native long Getlongvolatile (Object obj, long offset);
==> gets the value of the long field in the Obj object that corresponds to the offset shift address, and supports volatile load semantics.
==> obj: The object that contains the field that needs to be read
Offset of long field in ==>offset:<code>obj</code>


"11"
public native void Putlong (Object obj, long offset, long value);
==> sets the value of the long field in the Obj object that corresponds to the offset shift address to the specified value.
==>obj: Contains the object that needs to modify field
==>offset: Offset of long field in <code>obj</code>
==>value:field the new value to be set


"12"
Public native long Getlong (Object obj, long offset);
==> gets the value of the long field corresponding to offset offsets in the Obj object
==>obj: The object that contains the field that needs to be read
Offset of long field in ==>offset:<code>obj</code>

"13"
public native void Putobjectvolatile (object obj, long offset, object value);
==> sets the value of the Object field in the Obj object that corresponds to offset shift address to the specified value.
==>obj: Contains the object that needs to modify field
Offset of the object Type field in the ==>offset:<code>obj</code>
==>value:field the new value to be set

"14"
Public native object Getobjectvolatile (object obj, long offset);
==> gets the value of the type Object field in the Obj object that corresponds to offset offsets, and supports volatile load semantics.
==>obj: The object that contains the field that needs to be read
==>offset: Offset of object Type field in <code>obj</code>

xv
public native int Arraybaseoffset (Class arrayclass);
==> gets the offset address of the first element in a given array. In order to access the elements in the array, this offset address is associated with <a href= "#arrayIndexScale" ><code>arrayindexscale* </code></a> method is used together with a non-0 return value
==>arrayclass: The first element address gets the class
==> return: Offset address of the first element of the array

"16"
public native int Arrayindexscale (Class arrayclass);
==> gets the conversion factor for the user-given array addressing. When a suitable conversion factor cannot be returned (for example, the base type), return 0. This return value can be href= with <a "#arrayBaseOffset" ><code> Arraybaseoffset</code> </a> Use to access the elements in this array class

"17"
public native void Unpark (thread thread);
==> release is blocked by <a href= "#park" ><code>park</code></a> created on a thread. This method can also be used to terminate a previously called <code >park</code> caused by blocking. This operation is unsafe, so the thread must be guaranteed to be alive. This is the Java code, not the native code.
==>thread: the thread to unblock

"18"
Public native Void Park (Boolean isabsolute, long time);
==> blocks a thread until <a href= "#unpark" ><code>unpark</code></a> occurs, the thread is interrupted, or the timeout time expires. If a <code>unpark</code> call has already appeared, here only counts. A timeout of 0 means that it never expires. When <code>isAbsolute</code> is true, timeout is relative to the milliseconds after the new era. Otherwise this value is the number of nanoseconds before the timeout. This method may also be returned unreasonably when executed (no specific reason)
==>isabsolute: True if the value of timeout is a number of milliseconds after the new era
==>time: Can be a number of nanoseconds to wait, or a number of milliseconds after the new epoch until this point in time is reached

Java Programming: Unsafe classes

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.