Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีเรียก Garbage Collector (GC) ใน Java: 2 วิธี


Garbage Collection ใน Java ทำงานโดย daemon thread ชื่อ Garbage Collector (GC) แทนที่จะรอ JVM เราสามารถขอให้ JVM รัน GC ได้ แต่ ไม่มีการรับประกัน ว่า JVM จะรับคำขอหรือไม่

ใน Java เรียก GC ด้วยตนเองได้ 2 วิธี

  • ใช้คลาส System
  • ใช้คลาส Runtime

1. ใช้คลาส System

System มี static method gc() ใช้ขอให้ JVM เรียก garbage collector

ตัวอย่าง

public class SystemClassTest {
    public static void main(String[] args){
        SystemClassTest test = new SystemClassTest();
        test = null;
              System.gc(); 
    }

    public void finalize() {
        System.out.println("Garbage collected");
    }
}

ผลลัพธ์

Garbage collected

2. ใช้คลาส Runtime

Runtime เป็น singleton class ได้ออบเจ็กต์จาก getRuntime() เมธอด gc() เป็น instance method ของ Runtime

ตัวอย่าง

public class RuntimeClassTest {
    public static void main(String[] args) {
        RuntimeClassTest test = new RuntimeClassTest();
        test = null;
              Runtime.getRuntime().gc(); 
    }

    public void finalize() {
        System.out.println("Garbage Collected");
    }
}

ผลลัพธ์

Garbage collected