本文目錄一覽:
- 1、Java 的 DirectBuffer 是什麼東西
- 2、java ByteBuffer allocateDirect分配的是物理內存嗎
- 3、一道java題關於ByteBuffer.allocate()和ByteBuffer.allocateDirect
- 4、怎樣用Java獲取內存中的數據?
Java 的 DirectBuffer 是什麼東西
DirectByteBuffer 類有一個內部的靜態類 Deallocator,這個類實現了 Runnable 接口並在 run() 方法內釋放了內存:
unsafe.freeMemory(address);
那這個 Deallocator 線程是哪裡調用了呢?這裡就用到了 Java 的虛引用(PhantomReference),Java 虛引用允許對象被回收之前做一些清理工作。在 DirectByteBuffer 的構造方法中創建了一個
cleaner = Cleaner.create(this , new Deallocator(address, cap) ); 而Cleaner 類繼承了 PhantomReference 類,並且在自己的 clean() 方法中啟動了清理線程,當 DirectByteBuffer 被 GC 之前 cleaner 對象會被放入一個引用隊列(ReferenceQueue),JVM 會啟動一個低優先級線程掃描這個隊列,並且執行 Cleaner 的 clean 方法來做清理工作。OK,DirectByteBuffer 的實現大概搞清楚了,那我們是否該在自己的代碼中使用 DirectByteBuffer 呢?我個人認為可以適當的使用,使用直接內存確實避免了 GC 問題和內存拷貝的問題,但是我們不得不考慮兩個問題:1)操作系統可能會把 DirectByteBuffer 的內存交換到磁盤上,這樣勢必會影響性能,為了避免這個問題我們不得不對操作系統做相應的配置;2)DirectByteBuffer 申請內存失敗會直接拋出 OutOfMemoryError,對於這種情況,還是要想辦法處理。
java ByteBuffer allocateDirect分配的是物理內存嗎
當然是的啦,下面粘貼複製:
在Java中當我們要對數據進行更底層的操作時,通常是操作數據的位元組(byte)形式,這時常常會用到ByteBuffer這樣一個類。ByteBuffer提供了兩種靜態實例方式:
Java代碼
public static ByteBuffer allocate(int capacity)
public static ByteBuffer allocateDirect(int capacity)
為什麼要提供兩種方式呢?這與Java的內存使用機制有關。第一種分配方式產生的內存開銷是在JVM中的,而第二種的分配方式產生的開銷在JVM之外,以就是系統級的內存分配。
一道java題關於ByteBuffer.allocate()和ByteBuffer.allocateDirect
allocateDirect
public static ByteBuffer allocateDirect(int capacity)分配新的直接位元組緩衝區。
新緩衝區的位置將為零,其界限將為其容量,其標記是不確定的。無論它是否具有底層實現數組,其標記都是不確定的。
參數:
capacity – 新緩衝區的容量,以位元組為單位
allocate
public static ByteBuffer allocate(int capacity)分配一個新的位元組緩衝區。
新緩衝區的位置將為零,其界限將為其容量,其標記是不確定的。它將具有一個底層實現數組,且其 數組偏移量將為零。
參數:
capacity – 新緩衝區的容量,以位元組為單位
allocate和allocateDirect方法都做了相同的工作,不同的是allocateDirect方法直接使用操作系統來分配Buffer。因而它將提供更快的訪問速度。不幸的是,並非所有的虛擬機都支持這種直接分配的方法。
Sun推薦將以位元組為單位的直接型緩衝區allocateDirect用於與大型文件相關並具有較長生命周期的緩衝區。
怎樣用Java獲取內存中的數據?
方法如下:
首先
創建一個Bean用來存貯要得到的信
public class MonitorInfoBean {
/** 可使用內存. */
private long totalMemory;
/** 剩餘內存. */
private long freeMemory;
/** 最大可使用內存. */
private long maxMemory;
/** 操作系統. */
private String osName;
/** 總的物理內存. */
private long totalMemorySize;
/** 剩餘的物理內存. */
private long freePhysicalMemorySize;
/** 已使用的物理內存. */
private long usedMemory;
/** 線程總數. */
private int totalThread;
/** cpu使用率. */
private double cpuRatio;
public long getFreeMemory() {
return freeMemory;
}
public void setFreeMemory(long freeMemory) {
this.freeMemory = freeMemory;
}
public long getFreePhysicalMemorySize() {
return freePhysicalMemorySize;
}
public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
this.freePhysicalMemorySize = freePhysicalMemorySize;
}
public long getMaxMemory() {
return maxMemory;
}
public void setMaxMemory(long maxMemory) {
this.maxMemory = maxMemory;
}
public String getOsName() {
return osName;
}
public void setOsName(String osName) {
this.osName = osName;
}
public long getTotalMemory() {
return totalMemory;
}
public void setTotalMemory(long totalMemory) {
this.totalMemory = totalMemory;
}
public long getTotalMemorySize() {
return totalMemorySize;
}
public void setTotalMemorySize(long totalMemorySize) {
this.totalMemorySize = totalMemorySize;
}
public int getTotalThread() {
return totalThread;
}
public void setTotalThread(int totalThread) {
this.totalThread = totalThread;
}
public long getUsedMemory() {
return usedMemory;
}
public void setUsedMemory(long usedMemory) {
this.usedMemory = usedMemory;
}
public double getCpuRatio() {
return cpuRatio;
}
public void setCpuRatio(double cpuRatio) {
this.cpuRatio = cpuRatio;
}
}
之後,建立bean的接口
public interface IMonitorService {
public MonitorInfoBean getMonitorInfoBean() throws Exception;
}
然後,就是最關鍵的,得到cpu的利用率,已用內存,可用內存,最大內存等信息。
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import sun.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
import java.io.*;
import java.util.StringTokenizer;
/**
* 獲取系統信息的業務邏輯實現類.
* @author GuoHuang
*/
public class MonitorServiceImpl implements IMonitorService {
private static final int CPUTIME = 30;
private static final int PERCENT = 100;
private static final int FAULTLENGTH = 10;
private static final File versionFile = new File(“/proc/version”);
private static String linuxVersion = null;
/**
* 獲得當前的監控對象.
* @return 返回構造好的監控對象
* @throws Exception
* @author GuoHuang
*/
public MonitorInfoBean getMonitorInfoBean() throws Exception {
int kb = 1024;
// 可使用內存
long totalMemory = Runtime.getRuntime().totalMemory() / kb;
// 剩餘內存
long freeMemory = Runtime.getRuntime().freeMemory() / kb;
// 最大可使用內存
long maxMemory = Runtime.getRuntime().maxMemory() / kb;
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
// 操作系統
String osName = System.getProperty(“os.name”);
// 總的物理內存
long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
// 剩餘的物理內存
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
// 已使用的物理內存
long usedMemory = (osmxb.getTotalPhysicalMemorySize() – osmxb
.getFreePhysicalMemorySize())
/ kb;
// 獲得線程總數
ThreadGroup parentThread;
for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
.getParent() != null; parentThread = parentThread.getParent())
;
int totalThread = parentThread.activeCount();
double cpuRatio = 0;
if (osName.toLowerCase().startsWith(“windows”)) {
cpuRatio = this.getCpuRatioForWindows();
}
else {
cpuRatio = this.getCpuRateForLinux();
}
// 構造返回對象
MonitorInfoBean infoBean = new MonitorInfoBean();
infoBean.setFreeMemory(freeMemory);
infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
infoBean.setMaxMemory(maxMemory);
infoBean.setOsName(osName);
infoBean.setTotalMemory(totalMemory);
infoBean.setTotalMemorySize(totalMemorySize);
infoBean.setTotalThread(totalThread);
infoBean.setUsedMemory(usedMemory);
infoBean.setCpuRatio(cpuRatio);
return infoBean;
}
private static double getCpuRateForLinux(){
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
StringTokenizer tokenStat = null;
try{
System.out.println(“Get usage rate of CUP , linux version: “+linuxVersion);
Process process = Runtime.getRuntime().exec(“top -b -n 1”);
is = process.getInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
if(linuxVersion.equals(“2.4”)){
brStat.readLine();
brStat.readLine();
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
String user = tokenStat.nextToken();
tokenStat.nextToken();
String system = tokenStat.nextToken();
tokenStat.nextToken();
String nice = tokenStat.nextToken();
System.out.println(user+” , “+system+” , “+nice);
user = user.substring(0,user.indexOf(“%”));
system = system.substring(0,system.indexOf(“%”));
nice = nice.substring(0,nice.indexOf(“%”));
float userUsage = new Float(user).floatValue();
float systemUsage = new Float(system).floatValue();
float niceUsage = new Float(nice).floatValue();
return (userUsage+systemUsage+niceUsage)/100;
}else{
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
String cpuUsage = tokenStat.nextToken();
System.out.println(“CPU idle : “+cpuUsage);
Float usage = new Float(cpuUsage.substring(0,cpuUsage.indexOf(“%”)));
return (1-usage.floatValue()/100);
}
} catch(IOException ioe){
System.out.println(ioe.getMessage());
freeResource(is, isr, brStat);
return 1;
} finally{
freeResource(is, isr, brStat);
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/280478.html