Unsafe類操控物件 陣列 基本型別 CAS

2021-10-08 04:02:45 字數 3169 閱讀 4456

顧名思義,不安全的類。

通過這個類可以手動操控記憶體、執行緒,如果使用不當,會造成記憶體洩露,甚至jvm崩潰。

獲取unsafe

unsafe的構造器是私有的,無法通過new來獲得unsafe物件。

可以通過反射來獲取。

field unsafefield = unsafe.

class

.getdeclaredfield

("theunsafe"

);

unsafefield.

setaccessible

(true

);

unsafe unsafe =

(unsafe) unsafefield.

get(null)

;

操控基本型別
// allocate memory

long address = unsafe.

allocatememory

(8l)

;// put value

unsafe.

putint

(address,10)

;int num = unsafe.

getint

(address)

;

system.out.

println

(num)

;// free

unsafe.

freememory

(address)

;system.out.

println

(unsafe.

getaddress

(address)

);

操控執行緒
thread thread =

newthread((

)->

);

thread.

start()

;

timeunit.milliseconds.

sleep

(1l)

;// 恢復

unsafe.

unpark

(thread)

;

cas
data data =

newdata()

;data.

setid(1

);

data.

setage(2

);

field id = data.

getclass()

.getdeclaredfield

("id");

// get field offset

long fieldoffset = unsafe.

objectfieldoffset

(id)

;

id.setaccessible

(true

);

unsafe.

compareandswaplong

(data,fieldoffset,

1l,5l)

;

system.out.

println

(data.

getid()

);

運算元組
data[

] datas =

newdata[3

];datas[0]

=new

data

(6l)

;datas[1]

=new

data

(7l)

;datas[2]

=new

data

(8l)

;int baseoffset = unsafe.

arraybaseoffset

(data.

class);

int indexscale = unsafe.

arrayindexscale

(data.

class);

// 獲取第三個元素

object object = unsafe.

getobject

(datas, baseoffset+

(indexscale *2)

);system.out.

println((

(data)object)

.getid()

);// 修改 第二個元素

unsafe.

putobject

(datas,baseoffset+

(indexscale *1)

,new

data

(999l)

);

操作物件
data o =

(data)unsafe.

allocateinstance

(data.

class);

o.setid

(98798l)

;system.out.

println

(o.getid()

);field field = o.

getclass()

.getdeclaredfield

("id");

field.

setaccessible

(true);

long offset = unsafe.

objectfieldoffset

(field)

;long oldvalue = unsafe.

getandsetlong

(o, offset,

999l)

;unsafe.

putlong

(o,offset,

99999l)

;unsafe.

getandaddlong

(o,offset,1)

;system.out.

println

(o.getid()

);

陣列物件和類陣列物件區別

類陣列物件 看例子 var a var i 10 while i 10 很明顯物件啊 console.log a.length undefined 區別就在這了 類陣列物件沒有長度的屬性和陣列的方法 console.log object.prototype.tostring.call a objec...

陣列物件和類陣列物件區別

類陣列物件 看例子 var a var i 10 while i 10 很明顯物件啊 console.log a.length undefined 區別就在這了 類陣列物件沒有長度的屬性和陣列的方法 console.log object.prototype.tostring.call a objec...

陣列物件和類陣列物件區別

類陣列物件 看例子 var a var i 10 while i 10 很明顯物件啊 console.log a.length undefined 區別就在這了 類陣列物件沒有長度的屬性和陣列的方法 console.log object.prototype.tostring.call a objec...