ByteBuffer bookBuf = ByteBuffer.wrap("java 第一行代码".getBytes());
ByteBuffer wrap = ByteBuffer.wrap("xb".getBytes());
int len = bookBuf.limit();
int len2 = wrap.limit();
ByteBuffer[] bys = new ByteBuffer[]{bookBuf,wrap};
File file = new File("test.txt");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
FileChannel fc = fos.getChannel();
fc.write(bys);
fos.close();
//散读操作
ByteBuffer b1 = ByteBuffer.allocate(len);
ByteBuffer b2 = ByteBuffer.allocate(len2);
ByteBuffer[] b3 = new ByteBuffer[]{b1,b2};
File file1 =new File("test.txt");
FileInputStream fis = new FileInputStream(file1);
FileChannel fc1 = fis.getChannel();
fc1.read(b3);
String booName = new String(b3[0].array(),"UTF-8");
String userName = new String(b3[1].array(),"UTF-8");
private ByteBuffer byteBuffer;
public static void main(String[] args) throws Exception {
//write
DataOutputStream
dos =new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File("text.txt"))));
int numOfInts = 40000*40;
for(int i=0;i<numOfInts;i++){
dos.writeInt(i); //写入证书
}
if(dos!=null){
dos.close();
}
//read
DataInputStream dis = new DataInputStream(new
BufferedInputStream(new FileInputStream(
new File("text.txt")
)));
for (int i=0;i<numOfInts;i++){
int i1 = dis.readInt();
}
if(dis!=null){
dis.close();
}
//---------------------------------ByteBuffer Write
FileOutputStream fout = new FileOutputStream(new File("text.txt"));
FileChannel fc = fout.getChannel();
ByteBuffer byteBuffer= ByteBuffer.allocate(numOfInts*4);
for(int i=0;i<numOfInts;i++){
byteBuffer.put(int2Byte(i));
}
byteBuffer.flip();
fc.write(byteBuffer);
//---------------------------------ByteBuffer Read
FileInputStream fin = new FileInputStream(new File("test.txt"));
FileChannel fcb2 = fin.getChannel();
ByteBuffer byteBuffer1 = ByteBuffer.allocate(numOfInts*4);
fcb2.read(byteBuffer);
fc.close();
byteBuffer.flip();
while(byteBuffer.hasRemaining()){
byte2int(byteBuffer.get());
}
}
//位操作 将每4个byte转为int
private static void byte2int(byte b) {
byte[] target = new byte[4];
target[3]=(byte)(b&0xff);
target[2]=(byte)((b>>8)&0xff);
target[1]=(byte)((b>>16)&0xff);
target[0]=(byte)((b>>24)&0xff);
System.out.println(target);
}
private static byte[] int2Byte(int i) {
return (i+"").getBytes();
}
文件映射内存:
FileChannel fc = new RandomAccessFile("text.txt","rw").getChannel();
//文件映射内存
IntBuffer intBuffer = fc.map(FileChannel.MapMode.READ_WRITE, 0, 400000)
.asIntBuffer();
for(int i=0;i<10000;i++){
//写入文件
intBuffer.put(i);
}
fc.close();
//read
FileChannel fc2 = new RandomAccessFile("text.txt","rw").getChannel();
MappedByteBuffer map = fc2.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
IntBuffer intBuffer1 = map.asIntBuffer();
while(intBuffer.hasRemaining()){
System.out.println(intBuffer.get());
}
直接内存
public static void main(String[] args) {
//直接内存读取
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
try {
monDirectBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void monDirectBuffer() throws ClassNotFoundException,Exception,
NoSuchFileException{
Class c = Class.forName("java.nio.Bits");
Field maxMemory = c.getDeclaredField("maxMemory");
maxMemory.setAccessible(true);
Field reservedMemory = c.getDeclaredField("reservedMemory");
reservedMemory.setAccessible(true);
synchronized (c){
Object maxMemoryValue = maxMemory.get(null); //总大小
Object reservedMemoryValue = reservedMemory.get(null); //剩余大小
System.out.println("maxMemoryValue="+maxMemory);
System.out.println("reservedMemoryValue="+reservedMemoryValue);
}
}
引用:
强引用、软引用、弱引用、虚引用。
只有强引用FinalReference类是包内可见,其余3种类型均为Public。
强引用:
StringBuffer str= new StringBuffer("强引用");
如果这个代码是在函数上,那么栈上为局部变量,堆上为实例对象。
StringBuffer str1= str;
强引用特点:
强引用可以直接访问目标对象。
强引用锁指向的对象任何时候都不会被系统回收,JVM宁愿跑出OOM异常,也不会强制回收强引用。
强引用可能导致内存泄漏。
软引用:
除强引用,最强的引用,通过SoftReference使用软引用,一个软引用的对象不会很快被JVM回收,JVM会根据当前堆的使用情况来判断何时回收,当堆临近最大值,才会回收软引用。
软引用可以作用于:内存敏感的cache
弱引用:
系统GC,发现弱引用就会进行回收。
虚引用:
引用类型最弱,一个持有虚引用的对象和没有引用几乎一样的,随时都有可能别垃圾回收器回收。
E.g:
public class CanReliveObj {
public static CanReliveObj obj;
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("Can ReliveObj finalize called");
obj=this;
}
@Override
public String toString() {
return "I'm CanReliveObj";
}
public static void main(String[] args) throws InterruptedException {
obj = new CanReliveObj();
//创建引用队列
ReferenceQueue<CanReliveObj> phantomQueue = new ReferenceQueue();
//创建虚引用
PhantomReference<CanReliveObj> phantomReference=
new PhantomReference<>(obj,phantomQueue);
obj = null; //删除对象
System.gc(); //第一次GC
Thread.sleep(1000);
if(phantomReference.get()==null){
System.out.println("obj is null");
}else {
System.out.println("obj is not null");
}
System.out.println("第二次");
System.gc();
Thread.sleep(1000);
if(phantomReference.get()==null){
System.out.println("obj is null");
}else {
System.out.println("obj is not null");
}
}
}
public class Producer implements Runnable{
private volatile boolean flag;
private BlockingQueue<Integer> queue;
private static LongAdder count = new LongAdder();
public Producer(BlockingQueue<Integer> queue){
this.queue = queue;
System.out.println(this.flag);
}
@Override
public void run() {
Integer integer = null;
System.out.println("Start Producer id = "+Thread.currentThread().getId());
this.flag = true;
System.out.println(this.flag);
while(this.flag){
try {
count.increment();
int i = count.intValue();
System.out.println(i+" is put into queue!");
if(!queue.offer(i,2,TimeUnit.SECONDS)){
System.err.println("faild to put data: "+i);
}
System.out.println("push!!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void stop(){
flag=false;
}
}
class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
private static final int SLEEPTIME=1000;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
System.out.println("Start Consumer id="+Thread.currentThread().getId());
Random r = new Random();
while(true){
try {
Integer take = queue.take();
System.out.println("consumer take data is "+take);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
//缓冲区
BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(10);
Producer p = new Producer(blockingQueue);
Producer p1 = new Producer(blockingQueue);
Producer p2 = new Producer(blockingQueue);
Producer p3 = new Producer(blockingQueue);
Producer p4 = new Producer(blockingQueue);
ExecutorService service = Executors.newCachedThreadPool();
Consumer c = new Consumer(blockingQueue);
Consumer c1 = new Consumer(blockingQueue);
service.execute(p);
service.execute(p1);
service.execute(p2);
service.execute(p3);
service.execute(p4);
service.execute(c);
service.execute(c1);
p.stop();
p1.stop();
p2.stop();
p3.stop();
p4.stop();
Thread.sleep(3000);
}
线程池:
推荐使用该方法创建线程池,避免OOM,详细参见阿里编程规范。
corePoolSize 线程池中线程数量。
maximumPoolSize:线程池中最大线程数。
keepAliveTime:当线程池线程数量超过corePoolSize,多余的空闲线程存活时间(空闲线程多久被销毁)。
unit :keepAliveTime的时间单位.
workQueue:任务对了
handler:拒绝策略
CallerRunsPolicy :线程池未关闭一直执行。
AbortPolicy:超过创建线程池配置时,抛出异常。
DiscardPolicy:丢弃,不抛出异常。
DiscardOldestPolicy:丢弃之前的任务,重新执行
触发
------------------------------------------------------------------------------------------核心来了----------------------------------------------------
--------------------总结-------------------------