Theo dõi mức sử dụng bộ nhớ
Bạn đang phát triển một ứng dụng xử lý dữ liệu thao tác với các tập hợp đối tượng lớn. Hãy triển khai một tiện ích giám sát bộ nhớ giúp theo dõi mức tiêu thụ bộ nhớ trong các thao tác quan trọng để tránh lỗi OutOfMemoryError.
Bài tập này là một phần của khóa học
Tối ưu hóa mã trong Java
Hướng dẫn bài tập
- Lấy thể hiện JVM runtime hiện tại.
- Sử dụng tổng bộ nhớ và bộ nhớ trống của runtime để tính lượng bộ nhớ đang được sử dụng.
- Gọi phương thức để lấy bộ nhớ đã dùng tính theo megabyte.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
public class Main {
public static double getUsedMemoryMB() {
// Retrieve the JVM runtime instance
Runtime runtime = ____.____()
// Calculate the current used memory
long usedMemoryBytes = runtime.____() - runtime.____();
return usedMemoryBytes / (1024.0 * 1024.0);
}
public static void main(String[] args) {
double memoryBefore = getUsedMemoryMB();
System.out.println("Memory before array creation: " + memoryBefore + " MB");
int size = 10_000_000;
double[] largeArray = new double[size];
for (int i = 0; i < size; i++) {
largeArray[i] = Math.sqrt(i);
}
// Get the currently used memory in megabytes
double memoryAfter = ____();
System.out.println("Memory after array creation: " + memoryAfter + " MB");
System.out.println("Memory used by array creation: " + (memoryAfter - memoryBefore) + " MB");
}
}