java - What‘s the difference between volatile and UNSAFE.putIntVolatile() -


private static final long segshift_offset; segshift_offset = unsafe.objectfieldoffset(             concurrenthashmap.class.getdeclaredfield("segmentshift")); unsafe.putintvolatile(this, segshift_offset, 32); 

the code adove can replaced code follows?

private static volatile long segshift_offset = 0l;  segshift_offset = 32; 

or can replaced follows?

private static synchronized long sefshift_offset = 0l; segshift_offset = 32; 

i assume code have in class subclasses concurrenthashmap class.

no, cannot replaced suggest. code dangerous thing: updates package-private final field segmentshift of concurrenthashmap new value. segshift_offset used determine offset of segmentshift field within class (number of bytes between field location , beginning of object) in memory. offset assumed constant during jvm lifecycle, it's stored in final field.

your suggested replacements different thing: declare field , change value. way cannot change value of inaccessible final segmentshift field. it's updated using volatile semantic put memory barrier after update, other threads see updated value (though still doubt whether it's robust way this).

if want replace code, can try use reflection, though not impose volatile semantics necessary in case.

note unsafe code not work in jdk8, internal structure of concurrenthashmap changed , has no segmentshift field anymore. if want upgrade jdk8, reflection not either.

by way there's ongoing discussion removing unsafe completely.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -