gpt4 book ai didi

Java中的魔法类:sun.misc.Unsafe示例详解

转载 作者:qq735679552 更新时间:2022-09-28 22:32:09 27 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Java中的魔法类:sun.misc.Unsafe示例详解由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

前言 。

unsafe类在jdk 源码的多个类中用到,这个类的提供了一些绕开jvm的更底层功能,基于它的实现可以提高效率。但是,它是一把双刃剑:正如它的名字所预示的那样,它是unsafe的,它所分配的内存需要手动free(不被gc回收)。unsafe类,提供了jni某些功能的简单替代:确保高效性的同时,使事情变得更简单.

这个类是属于sun.* api中的类,并且它不是j2se中真正的一部份,因此你可能找不到任何的官方文档,更可悲的是,它也没有比较好的代码文档.

这篇文章主要是以下文章的整理、翻译.

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

1. unsafe api的大部分方法都是native实现,它由105个方法组成,主要包括以下几类:

(1)info相关。主要返回某些低级别的内存信息:addresssize(), pagesize() 。

(2)objects相关。主要提供object和它的域操纵方法:allocateinstance(),objectfieldoffset() 。

(3)class相关。主要提供class和它的静态域操纵方法:staticfieldoffset(),defineclass(),defineanonymousclass(),ensureclassinitialized() 。

(4)arrays相关。数组操纵方法:arraybaseoffset(),arrayindexscale() 。

(5)synchronization相关。主要提供低级别同步原语(如基于cpu的cas(compare-and-swap)原语):monitorenter(),trymonitorenter(),monitorexit(),compareandswapint(),putorderedint() 。

(6)memory相关。直接内存访问方法(绕过jvm堆直接操纵本地内存):allocatememory(),copymemory(),freememory(),getaddress(),getint(),putint() 。

2. unsafe类实例的获取 。

unsafe类设计只提供给jvm信任的启动类加载器所使用,是一个典型的单例模式类。它的实例获取方法如下:

?
1
2
3
4
5
6
public static unsafe getunsafe() {
  class cc = sun.reflect.reflection.getcallerclass( 2 );
  if (cc.getclassloader() != null )
   throw new securityexception( "unsafe" );
  return theunsafe;
}

非启动类加载器直接调用unsafe.getunsafe()方法会抛出securityexception(具体原因涉及jvm类的双亲加载机制).

解决办法有两个,其一是通过jvm参数-xbootclasspath指定要使用的类为启动类,另外一个办法就是java反射了.

?
1
2
3
field f = unsafe. class .getdeclaredfield( "theunsafe" );
f.setaccessible( true );
unsafe unsafe = (unsafe) f.get( null );

通过将private单例实例暴力设置accessible为true,然后通过field的get方法,直接获取一个object强制转换为unsafe。在ide中,这些方法会被标志为error,可以通过以下设置解决:

?
1
2
preferences -> java -> compiler -> errors/warnings ->
deprecated and restricted api -> forbidden reference -> warning

3. unsafe类“有趣”的应用场景 。

(1)绕过类初始化方法。当你想要绕过对象构造方法、安全检查器或者没有public的构造方法时,allocateinstance()方法变得非常有用.

?
1
2
3
4
5
6
7
class a {
  private long a; // not initialized value
  public a() {
   this .a = 1 ; // initialization
  }
  public long a() { return this .a; }
}

以下是构造方法、反射方法和allocateinstance()的对照 。

?
1
2
3
4
5
6
7
8
a o1 = new a(); // constructor
o1.a(); // prints 1
 
a o2 = a. class .newinstance(); // reflection
o2.a(); // prints 1
 
a o3 = (a) unsafe.allocateinstance(a. class ); // unsafe
o3.a(); // prints 0

allocateinstance()根本没有进入构造方法,在单例模式时,我们似乎看到了危机.

(2)内存修改 。

内存修改在c语言中是比较常见的,在java中,可以用它绕过安全检查器.

考虑以下简单准入检查规则:

?
1
2
3
4
5
6
7
class guard {
  private int access_allowed = 1 ;
 
  public boolean giveaccess() {
   return 42 == access_allowed;
  }
}

在正常情况下,giveaccess总会返回false,但事情不总是这样 。

?
1
2
3
4
5
6
7
8
9
guard guard = new guard();
guard.giveaccess(); // false, no access
 
// bypass
unsafe unsafe = getunsafe();
field f = guard.getclass().getdeclaredfield( "access_allowed" );
unsafe.putint(guard, unsafe.objectfieldoffset(f), 42 ); // memory corruption
 
guard.giveaccess(); // true, access granted

通过计算内存偏移,并使用putint()方法,类的access_allowed被修改。在已知类结构的时候,数据的偏移总是可以计算出来(与c++中的类中数据的偏移计算是一致的).

(3)实现类似c语言的sizeof()函数 。

通过结合java反射和objectfieldoffset()函数实现一个c-like sizeof()函数.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static long sizeof(object o) {
  unsafe u = getunsafe();
  hashset fields = new hashset();
  class c = o.getclass();
  while (c != object. class ) {
   for (field f : c.getdeclaredfields()) {
    if ((f.getmodifiers() & modifier. static ) == 0 ) {
     fields.add(f);
    }
   }
   c = c.getsuperclass();
  }
 
  // get offset
  long maxsize = 0 ;
  for (field f : fields) {
   long offset = u.objectfieldoffset(f);
   if (offset > maxsize) {
    maxsize = offset;
   }
  }
  return ((maxsize/ 8 ) + 1 ) * 8 ; // padding
}

算法的思路非常清晰:从底层子类开始,依次取出它自己和它的所有超类的非静态域,放置到一个hashset中(重复的只计算一次,java是单继承),然后使用objectfieldoffset()获得一个最大偏移,最后还考虑了对齐.

在32位的jvm中,可以通过读取class文件偏移为12的long来获取size.

?
1
2
3
4
public static long sizeof(object object){
  return getunsafe().getaddress(
   normalize(getunsafe().getint(object, 4l)) + 12l);
}

其中normalize()函数是一个将有符号int转为无符号long的方法 。

?
1
2
3
4
private static long normalize( int value) {
  if (value >= 0 ) return value;
  return (0l >>> 32 ) & value;
}

两个sizeof()计算的类的尺寸是一致的。最标准的sizeof()实现是使用java.lang.instrument,但是,它需要指定命令行参数-javaagent.

(4)实现java浅复制 。

标准的浅复制方案是实现cloneable接口或者自己实现的复制函数,它们都不是多用途的函数。通过结合sizeof()方法,可以实现浅复制.

?
1
2
3
4
5
6
7
static object shallowcopy(object obj) {
  long size = sizeof(obj);
  long start = toaddress(obj);
  long address = getunsafe().allocatememory(size);
  getunsafe().copymemory(start, address, size);
  return fromaddress(address);
}

以下的toaddress()和fromaddress()分别将对象转换到它的地址以及相反操作.

?
1
2
3
4
5
6
7
8
9
10
11
12
static long toaddress(object obj) {
  object[] array = new object[] {obj};
  long baseoffset = getunsafe().arraybaseoffset(object[]. class );
  return normalize(getunsafe().getint(array, baseoffset));
}
 
static object fromaddress( long address) {
  object[] array = new object[] { null };
  long baseoffset = getunsafe().arraybaseoffset(object[]. class );
  getunsafe().putlong(array, baseoffset, address);
  return array[ 0 ];
}

以上的浅复制函数可以应用于任意java对象,它的尺寸是动态计算的.

(5)消去内存中的密码 。

密码字段存储在string中,但是,string的回收是受到jvm管理的。最安全的做法是,在密码字段使用完之后,将它的值覆盖.

?
1
2
3
4
5
6
field stringvalue = string. class .getdeclaredfield( "value" );
stringvalue.setaccessible( true );
char [] mem = ( char []) stringvalue.get(password);
for ( int i= 0 ; i < mem.length; i++) {
  mem[i] = '?' ;
}

(6)动态加载类 。

标准的动态加载类的方法是class.forname()(在编写jdbc程序时,记忆深刻),使用unsafe也可以动态加载java 的class文件.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
byte [] classcontents = getclasscontent();
class c = getunsafe().defineclass(
     null , classcontents, 0 , classcontents.length);
  c.getmethod( "a" ).invoke(c.newinstance(), null ); // 1
getclasscontent()方法,将一个 class 文件,读取到一个 byte 数组。
 
private static byte [] getclasscontent() throws exception {
  file f = new file( "/home/mishadoff/tmp/a.class" );
  fileinputstream input = new fileinputstream(f);
  byte [] content = new byte [( int )f.length()];
  input.read(content);
  input.close();
  return content;
}

动态加载、代理、切片等功能中可以应用.

(7)包装受检异常为运行时异常.

?
1
getunsafe().throwexception( new ioexception());

当你不希望捕获受检异常时,可以这样做(并不推荐).

(8)快速序列化 。

标准的java serializable速度很慢,它还限制类必须有public无参构造函数。externalizable好些,它需要为要序列化的类指定模式。流行的高效序列化库,比如kryo依赖于第三方库,会增加内存的消耗。可以通过getint(),getlong(),getobject()等方法获取类中的域的实际值,将类名称等信息一起持久化到文件。kryo有使用unsafe的尝试,但是没有具体的性能提升的数据。(http://code.google.com/p/kryo/issues/detail?id=75) 。

(9)在非java堆中分配内存 。

使用java 的new会在堆中为对象分配内存,并且对象的生命周期内,会被jvm gc管理.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class superarray {
  private final static int byte = 1 ;
 
  private long size;
  private long address;
 
  public superarray( long size) {
   this .size = size;
   address = getunsafe().allocatememory(size * byte );
  }
 
  public void set( long i, byte value) {
   getunsafe().putbyte(address + i * byte , value);
  }
 
  public int get( long idx) {
   return getunsafe().getbyte(address + idx * byte );
  }
 
  public long size() {
   return size;
  }
}

unsafe分配的内存,不受integer.max_value的限制,并且分配在非堆内存,使用它时,需要非常谨慎:忘记手动回收时,会产生内存泄露;非法的地址访问时,会导致jvm崩溃。在需要分配大的连续区域、实时编程(不能容忍jvm延迟)时,可以使用它。java.nio使用这一技术.

(10)java并发中的应用 。

通过使用unsafe.compareandswap()可以用来实现高效的无锁数据结构.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class cascounter implements counter {
  private volatile long counter = 0 ;
  private unsafe unsafe;
  private long offset;
 
  public cascounter() throws exception {
   unsafe = getunsafe();
   offset = unsafe.objectfieldoffset(cascounter. class .getdeclaredfield( "counter" ));
  }
 
  @override
  public void increment() {
   long before = counter;
   while (!unsafe.compareandswaplong( this , offset, before, before + 1 )) {
    before = counter;
   }
  }
 
  @override
  public long getcounter() {
   return counter;
  }
}

通过测试,以上数据结构与java的原子变量的效率基本一致,java原子变量也使用unsafe的compareandswap()方法,而这个方法最终会对应到cpu的对应原语,因此,它的效率非常高。这里有一个实现无锁hashmap的方案(http://www.azulsystems.com/about_us/presentations/lock-free-hash ,这个方案的思路是:分析各个状态,创建拷贝,修改拷贝,使用cas原语,自旋锁),在普通的服务器机器(核心<32),使用concurrenthashmap(jdk8以前,默认16路分离锁实现,jdk8中concurrenthashmap已经使用无锁实现)明显已经够用.

总结 。

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对我的支持.

原文链接:https://www.cnblogs.com/suxuan/p/4948608.html 。

最后此篇关于Java中的魔法类:sun.misc.Unsafe示例详解的文章就讲到这里了,如果你想了解更多关于Java中的魔法类:sun.misc.Unsafe示例详解的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com