目录
Java申请DirectBuffer
/*-------JAVA直接操作内存------------- * 申请100m的直接内存,不会申请在java堆上面 * 打开资源管理器可以看到内存占用会增加100m,但是java堆上的内存却没有增加! */ByteBuffer buffer = ByteBuffer.allocateDirect(100 * 1024 * 1024);System.out.println("------------------start----------------------");Thread.sleep(10 * 1000);// 清理刚刚申请的内存
((DirectBuffer)(buffer)).cleaner().clean(); System.out.println("------------------end----------------------");
ByteBuffer的position,limit,capacity,flip操作之间的关系
以下面的代码为例
/*** 描述:测试ByteBuffer的相关操作* position:写模式下当前写的位置,读模式下当前读的位置* limit:写模式下能写多少数据,读模式下能读多少数据* capacity:即byteBuffer的总大小,不区分读写* flip:将limit置为position,position置为0,一般用于写完之后开始进行读取*/ privatestaticvoid testByteBufferOperation() throws InterruptedException {
ByteBuffer buffer = ByteBuffer.allocate(20); buffer.putInt(123); //java 1个int 4个字节 //默认limit和capacity的值是相同的,第一次put之后,position移动到当前写的位置
System.out.println("*************initial status***************");
System.out.println("position:" + buffer.position() + "\nlimit:" + buffer.limit() + "\n"
+ "capacity:" + buffer.capacity()); //flip之后,limit变为position,position置为0
buffer.flip();
System.out.println("*************after flip***************");
System.out.println("position:" + buffer.position() + "\nlimit:" + buffer.limit() + "\n"
+ "capacity:" + buffer.capacity()); //get之后,position移动1位,其他不变
buffer.get();
System.out.println("*************after first get***************");
System.out.println("position:" + buffer.position() + "\nlimit:" + buffer.limit() + "\n"
+ "capacity:" + buffer.capacity());
}
枚举实现单例模式
/* * 枚举实现单例,一方面保证了线程安全,另一方面会“免费”得到了序列化的功能
*/publicenum ChildEnum {
//枚举里面默认的实例
INSTANCE;
private Child childInstance; private ChildEnum()
{
childInstance = new Child();
} public Child getInstance()
{
returnchildInstance;
}
}