Demi 6 months ago
parent
commit
181d5c96d3

+ 15 - 0
lesson/src/com/sf/jvm/HeapOOM.java

@@ -0,0 +1,15 @@
+package com.sf.jvm;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class HeapOOM {
+
+    static class OOMObject{}
+    public static void main(String[] args) {
+        List<OOMObject> list = new ArrayList<OOMObject>();
+        while (true){
+            list.add(new OOMObject());
+        }
+    }
+}

+ 19 - 0
lesson/src/com/sf/jvm/RuntimeDemo.java

@@ -0,0 +1,19 @@
+package com.sf.jvm;
+
+public class RuntimeDemo {
+
+    public static void main(String[] args) {
+        // 获取运行时环境
+        Runtime runtime = Runtime.getRuntime();
+        // 最大可用内存
+        long maxMemory = runtime.maxMemory();
+        // 已获得内存
+        long totalMemory = runtime.totalMemory();
+
+        // CPU核数
+        int processors = runtime.availableProcessors();
+        System.out.println("Max Memory: " + maxMemory/1024/1024 + "MB");
+        System.out.println("Total Memory: " + totalMemory/1024/1024 + "MB");
+        System.out.println("Processors: " + processors);
+    }
+}

+ 22 - 0
lesson/src/com/sf/jvm/StackSOF.java

@@ -0,0 +1,22 @@
+package com.sf.jvm;
+
+public class StackSOF {
+
+    // 调用的深度
+    private int stackLength = 1;
+
+    public void stackLeak() {
+        stackLength++;
+        stackLeak();
+    }
+
+    public static void main(String[] args) {
+        StackSOF sof = new StackSOF();
+        try {
+            sof.stackLeak();
+        } catch (Throwable e) {
+            System.out.println("stack length: " + sof.stackLength);
+            throw e;
+        }
+    }
+}

+ 28 - 0
lesson/src/com/sf/jvm/ref/SoftRefDemo.java

@@ -0,0 +1,28 @@
+package com.sf.jvm.ref;
+
+import java.lang.ref.SoftReference;
+
+public class SoftRefDemo {
+
+    static class DataBlock{
+        private final byte[] bytes;
+
+        public DataBlock(int byteCount){
+            this.bytes = new byte[byteCount];
+        }
+
+        public String toString(){
+            return "DataBlock { byteCount = " + bytes.length + "}";
+        }
+    }
+
+    public static void main(String[] args) {
+        // 1024 * 1024 * 10 = 10MB
+        SoftReference<DataBlock> softRef = new SoftReference<DataBlock>(
+                new DataBlock(1024 * 1024 * 8));
+        // 获取软引用对象
+        System.out.println(softRef.get());
+        byte[] other = new byte[1024 * 1024 * 8];
+        System.out.println(softRef.get());
+    }
+}

+ 14 - 0
lesson/src/com/sf/jvm/ref/WeakRefDemo.java

@@ -0,0 +1,14 @@
+package com.sf.jvm.ref;
+
+import java.lang.ref.WeakReference;
+
+public class WeakRefDemo {
+
+    public static void main(String[] args) throws Exception {
+        WeakReference<String> weakRef = new WeakReference<>(new String("Hello"));
+        System.out.println(weakRef.get());
+        // 触发垃圾回收
+        System.gc();
+        System.out.println(weakRef.get());
+    }
+}