Mục lục
Hướng dẫn và ví dụ Java PhantomReference
Xem thêm các chuyên mục:

Là một website được viết trên công nghệ web Flutter vì vậy hỗ trợ rất tốt cho người học, kể cả những người học khó tính nhất.
Hiện tại website đang tiếp tục được cập nhập nội dung cho phong phú và đầy đủ hơn. Mong các bạn nghé thăm và ủng hộ website mới của chúng tôi.


Trong bài viết này, chúng ta sẽ thảo luận về lớp PhantomReference, trước khi bắt đầu tôi khuyến nghị bạn nên tìm hiểu về lớp WeakReference và SoftReference. Cả 3 lớp này có các đặc điểm cơ bản giống nhau và không cần thiết phải được đề cập lại một lần nữa.

PhantomReference Constructors
PhantomReference(T innerObject, ReferenceQueue<? super T> queue)
PhantomReference chỉ có duy nhất một constructor. Để tạo một đối tượng PhantomReference bạn phải cung cấp cho 2 tham số:
- innerObject: Đối tượng sẽ được gói bên trong đối tượng PhantomReference.
- queue: Một hàng đợi được sử dụng để lưu trữ đối tượng PhantomReference này khi đối tượng innerObject của nó bị GC xoá khỏi bộ nhớ.
ReferenceQueue<AnyObject> queue = new ReferenceQueue<>();
AnyObject innerObject = new AnyObject("Obj1");
PhantomReference phantomRef = new PhantomReference(innerObject, queue);
Tất cả các phương thức của PhantomReference được thừa kế từ lớp cha.
// Methods inherited from parent.
public T get()
public void clear()
public boolean isEnqueued()
public boolean enqueue()
Phương thức phantomReference.get() luôn luôn trả về null, mục đích là ngăn chặn việc truy cập hoặc ý muốn hồi sinh một đối tượng gần như đã bị loại bỏ.

Có thể bạn đang ngạc nhiên về các đặc điểm của PhantomReference và câu hỏi của bạn lúc này là PhantomReference được sử dụng cho mục đích gì?
PhantomReference phantomRef = new PhantomReference(innerObject, queue);
Về cơ bản PhantomReference cung cấp cho bạn khả năng xác định chính xác khi nào đối tượng innerObject của nó bị xoá khỏi bộ nhớ. Phương thức phantomRef.isEnqueued() trả về true nghĩa là đối tượng innerObject đã bị xoá bỏ khỏi bộ nhớ. Khi đối tượng innerObject bị xoá khỏi bộ nhớ thì đối tượng phantomRef sẽ được đặt vào hàng đợi (queue).
Ví dụ: Nếu bạn cần cấp phát bộ nhớ để xử lý các tệp video lớn thì việc sử dụng PhantomReference là một lựa chọn đúng đắn. Ban đầu sử dụng PhantomReference cấp phát bộ nhớ để xử lý video đầu tiên, sau đó bạn cần kiểm tra để đảm bảo rằng bộ nhớ đó đã được giải phóng trước khi tiếp tục cấp phát bộ nhớ để xử lý tệp video tiếp theo. Điều này làm giảm bớt nguy cơ nhận được OutOfMemoryError.
Lớp VideoProcessor mô phỏng việc xử lý một tệp video kích thước lớn:
VideoProcessor.java
package org.o7planning.phantomreference.ex;
public class VideoProcessor {
private String video;
public VideoProcessor(String video) {
this.video = video;
System.out.println("\nNew VideoProcessor: " + this.video);
}
public void process() {
System.out.println(" >>> Processing video: " + this.video);
try {
Thread.sleep(2000);
} catch (InterruptedException e) { }
System.out.println(" >>> Completed processing video: " + this.video);
}
// !IMPORTANT: Do not override finalize() method.
// (Java9+: If you override this method, PhantomReference will not work!!)
// @Override
// protected void finalize() throws Throwable {
// System.out.println("VideoProcessor is being removed from memory\n");
// super.finalize();
// }
}
PhantomReferenceEx1.java
package org.o7planning.phantomreference.ex;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
public class PhantomReferenceEx1 {
public static void main(String[] args) {
String[] videos = new String[] { "video1.mp4", "video2.mp4", "video3.mp4" };
ReferenceQueue<VideoProcessor> queue = new ReferenceQueue<VideoProcessor>();
for (String video : videos) {
VideoProcessor videoProcessor = new VideoProcessor(video);
PhantomReference<VideoProcessor> phantomRef = new PhantomReference<>(videoProcessor, queue);
videoProcessor.process();
videoProcessor = null;
// Call GC:
System.gc();
while (true) {
boolean isEnqueued = phantomRef.isEnqueued();
System.out.println(" phantomRef.isEnqueued: " + isEnqueued);
if (!isEnqueued) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
continue;
}
break;
}
}
System.out.println("\nObjects in the queue:");
Reference<? extends VideoProcessor> ref= null;
while((ref = queue.poll())!= null) {
System.out.println(ref);
}
}
}
Output:
New VideoProcessor: video1.mp4
>>> Processing video: video1.mp4
>>> Completed processing video: video1.mp4
phantomRef.isEnqueued: false
phantomRef.isEnqueued: true
New VideoProcessor: video2.mp4
>>> Processing video: video2.mp4
>>> Completed processing video: video2.mp4
phantomRef.isEnqueued: false
phantomRef.isEnqueued: true
New VideoProcessor: video3.mp4
>>> Processing video: video3.mp4
>>> Completed processing video: video3.mp4
phantomRef.isEnqueued: false
phantomRef.isEnqueued: true
Objects in the queue:
java.lang.ref.PhantomReference@5e265ba4
java.lang.ref.PhantomReference@156643d4
java.lang.ref.PhantomReference@123a439b