下面列出了java.lang.management.MemoryUsage#getUsed ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void paintComponent(Graphics g) {
MemoryUsage mem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
double used = mem.getUsed();
double maxi = mem.getMax();
peak = Math.max(used, peak);
super.paintComponent(g);
int w = getWidth();
g.setColor(colorBackground);
for(int i=0; i<w; i+=w/10)
g.drawLine(i, 0, i, 30);
int posu = (int)Math.round(w*used/maxi);
int posp = (int)Math.round(w*peak/maxi);
String u = NumFormat.bytes(used);
g.setColor(colorHot);
g.fillRect(0, 0, posu, 30);
g.fillRect(0, 0, posp, 30);
g.setColor(colorText);
g.drawString(prefix + u, 10, 17);
}
public boolean isUsageThresholdExceeded() {
if (!isUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"Usage threshold is not supported");
}
// return false if usage threshold crossing checking is disabled
if (usageThreshold == 0) {
return false;
}
MemoryUsage u = getUsage0();
return (u.getUsed() >= usageThreshold ||
usageSensor.isOn());
}
public boolean isUsageThresholdExceeded() {
if (!isUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"Usage threshold is not supported");
}
// return false if usage threshold crossing checking is disabled
if (usageThreshold == 0) {
return false;
}
MemoryUsage u = getUsage0();
return (u.getUsed() >= usageThreshold ||
usageSensor.isOn());
}
public long getEdenUsed()
throws JMException
{
CompositeData data
= (CompositeData) _mbeanServer.getAttribute(getEdenName(), "Usage");
MemoryUsage usage = MemoryUsage.from(data);
return usage.getUsed();
}
public static void printMemoryUsage(String label) {
MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
label,
humanReadableByteCount(memusage.getInit(), false),
humanReadableByteCount(memusage.getUsed(), false),
humanReadableByteCount(memusage.getCommitted(), false),
freeratio * 100
);
}
public static void printMemoryUsage(String label) {
MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
label,
humanReadableByteCount(memusage.getInit(), false),
humanReadableByteCount(memusage.getUsed(), false),
humanReadableByteCount(memusage.getCommitted(), false),
freeratio * 100
);
}
public static void printMemoryUsage(String label) {
MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
label,
humanReadableByteCount(memusage.getInit(), false),
humanReadableByteCount(memusage.getUsed(), false),
humanReadableByteCount(memusage.getCommitted(), false),
freeratio * 100
);
}
public boolean isUsageThresholdExceeded() {
if (!isUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"Usage threshold is not supported");
}
// return false if usage threshold crossing checking is disabled
if (usageThreshold == 0) {
return false;
}
MemoryUsage u = getUsage0();
return (u.getUsed() >= usageThreshold ||
usageSensor.isOn());
}
public boolean isCollectionUsageThresholdExceeded() {
if (!isCollectionUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"CollectionUsage threshold is not supported");
}
// return false if usage threshold crossing checking is disabled
if (collectionThreshold == 0) {
return false;
}
MemoryUsage u = getCollectionUsage0();
return (gcSensor.isOn() ||
(u != null && u.getUsed() >= collectionThreshold));
}
public static void printMemoryUsage(String label) {
MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
label,
humanReadableByteCount(memusage.getInit(), false),
humanReadableByteCount(memusage.getUsed(), false),
humanReadableByteCount(memusage.getCommitted(), false),
freeratio * 100
);
}
public static void printMemoryUsage(String label) {
MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
label,
humanReadableByteCount(memusage.getInit(), false),
humanReadableByteCount(memusage.getUsed(), false),
humanReadableByteCount(memusage.getCommitted(), false),
freeratio * 100
);
}
public boolean isCollectionUsageThresholdExceeded() {
if (!isCollectionUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"CollectionUsage threshold is not supported");
}
// return false if usage threshold crossing checking is disabled
if (collectionThreshold == 0) {
return false;
}
MemoryUsage u = getCollectionUsage0();
return (gcSensor.isOn() ||
(u != null && u.getUsed() >= collectionThreshold));
}
public boolean isUsageThresholdExceeded() {
if (!isUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"Usage threshold is not supported");
}
// return false if usage threshold crossing checking is disabled
if (usageThreshold == 0) {
return false;
}
MemoryUsage u = getUsage0();
return (u.getUsed() >= usageThreshold ||
usageSensor.isOn());
}
public boolean isCollectionUsageThresholdExceeded() {
if (!isCollectionUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"CollectionUsage threshold is not supported");
}
// return false if usage threshold crossing checking is disabled
if (collectionThreshold == 0) {
return false;
}
MemoryUsage u = getCollectionUsage0();
return (gcSensor.isOn() ||
(u != null && u.getUsed() >= collectionThreshold));
}
public boolean isUsageThresholdExceeded() {
if (!isUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"Usage threshold is not supported");
}
// return false if usage threshold crossing checking is disabled
if (usageThreshold == 0) {
return false;
}
MemoryUsage u = getUsage0();
return (u.getUsed() >= usageThreshold ||
usageSensor.isOn());
}
protected int getNumberOfThreads (List<ServerInfo> serverInfoList, List<DiskStoreImpl> diskStores) {
/****
* As we extract one diskstore at a time for a given server.
* Here the logic is we find the largest disk-store and use its size as a basis for worst case heap memory required
* for salvaging a server at a given time.
* This helps in determining how may servers can we salvage in parallel for given heap memory.
* This is a very conservative estimate.
*/
long maxDiskStoreSizeOnDisk = 0;
int maxNumberOfServersInParallel = 1;
final double mbDiv = Math.pow(1024, 2);
for (ServerInfo serverInfo : serverInfoList) {
long maxDiskStoreSizeForServer = ExtractorUtils.getMaxDiskStoreSizeForServer(serverInfo, diskStores);
if (maxDiskStoreSizeOnDisk < maxDiskStoreSizeForServer) {
maxDiskStoreSizeOnDisk = maxDiskStoreSizeForServer;
}
}
logInfo("Maximum disk-store size on disk " + maxDiskStoreSizeOnDisk/mbDiv + " MB");
MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapMemUsage = memBean.getHeapMemoryUsage();
long usedMemory = heapMemUsage.getUsed();
long committedMemory = heapMemUsage.getCommitted();
//For safety using the committedMemory for calculation, as it is the memory that is guaranteed to be available for the VM.
long availableMemory = (committedMemory - usedMemory);
logInfo("Available memory : " + availableMemory/mbDiv + " MB");
double maxMemoryPerServer = (2.2)*maxDiskStoreSizeOnDisk;
//Setting the lower limit
if (maxMemoryPerServer < 1) {
maxMemoryPerServer = 1;
}
logInfo("Estimated memory needed per server : " + maxMemoryPerServer/mbDiv + " MB");
if (availableMemory < maxMemoryPerServer) {
logWarning("Not enough memory to extract the server, extractor could possibly run out of memory");
}
maxNumberOfServersInParallel = (int) (availableMemory/maxMemoryPerServer);
if (maxNumberOfServersInParallel < 1) {
maxNumberOfServersInParallel = 1;
}
logInfo("Recommended number of threads to extract server(s) in parallel : " + maxNumberOfServersInParallel);
return maxNumberOfServersInParallel;
}
public void installMonitor(){
//get all the GarbageCollectorMXBeans - there's one for each heap generation
//so probably two - the old generation and young generation
List<GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
//Install a notification handler for each bean
for (GarbageCollectorMXBean gcbean : gcbeans) {
NotificationEmitter emitter = (NotificationEmitter) gcbean;
//use an anonymously generated listener for this example
// - proper code should really use a named class
NotificationListener listener = new NotificationListener() {
//keep a count of the total time spent in GCs
long totalGcDuration = 0;
//implement the notifier callback handler
@Override
public void handleNotification(Notification notification, Object handback) {
//we only handle GARBAGE_COLLECTION_NOTIFICATION notifications here
if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
//get the information associated with this notification
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());
//get all the info and pretty print it
//Get the information about each memory space, and pretty print it
Map<String, MemoryUsage> membefore = info.getGcInfo().getMemoryUsageBeforeGc();
Map<String, MemoryUsage> mem = info.getGcInfo().getMemoryUsageAfterGc();
long memInit=0;
long memCommitted=0;
long memMax=0;
long memUsed=0;
// MemoryUsage before;
for (Map.Entry<String, MemoryUsage> entry : mem.entrySet()) {
String name = entry.getKey();
MemoryUsage memdetail = entry.getValue();
memInit += memdetail.getInit();
memCommitted += memdetail.getCommitted();
memMax += memdetail.getMax();
memUsed += memdetail.getUsed();
// MemoryUsage before = membefore.get(name);
// System.out.print(name + (memCommitted==memMax?"(fully expanded)":"(still expandable)") +"used: "+(beforepercent/10)+"."+(beforepercent%10)+"%->"+(percent/10)+"."+(percent%10)+"%("+((memUsed/1048576)+1)+"MB) / ");
}
// System.out.println(" Mem max (max used or available?)"+memMax/100000+" mem used (before or after?)"+memUsed/100000+" mem committed? ="+memCommitted/1000000);
if(memMax>maxMemMax)
maxMemMax=memMax;
if(memUsed>maxMemUsed)
maxMemUsed=memUsed;
if(memCommitted>maxMemCommitted)
maxMemCommitted= memCommitted;
}
}
};
//Add the listener
emitter.addNotificationListener(listener, null, null);
}
}
public static double getHeapMemoryUsed() {
MemoryMXBean bean = ManagementFactory.getMemoryMXBean();
MemoryUsage usage = bean.getHeapMemoryUsage();
long bytes = usage.getUsed();
return bytes / 1.0e6;
}
public static void createGoodCompositeData() throws Exception {
final int K = 1024;
// these values are synchronized with the item names
final Object[] values = {
new Long(5 * K), // committed
new Long(1 * K), // init
new Long(10 * K), // max
new Long(2 * K), // used
"Dummy",
"Dummy",
};
CompositeType muct =
new CompositeType("MyMemoryUsageCompositeType",
"CompositeType for MemoryUsage",
memoryUsageItemNames,
memoryUsageItemNames,
memoryUsageItemTypes);
CompositeData cd =
new CompositeDataSupport(muct,
memoryUsageItemNames,
values);
MemoryUsage u = MemoryUsage.from(cd);
if (u.getInit() != ((Long) values[INIT]).longValue()) {
throw new RuntimeException("init = " + u.getInit() +
" expected = " + values[INIT]);
}
if (u.getUsed() != ((Long) values[USED]).longValue()) {
throw new RuntimeException("used = " + u.getUsed() +
" expected = " + values[USED]);
}
if (u.getCommitted() != ((Long) values[COMMITTED]).longValue()) {
throw new RuntimeException("committed = " + u.getCommitted() +
" expected = " + values[COMMITTED]);
}
if (u.getMax() != ((Long) values[MAX]).longValue()) {
throw new RuntimeException("max = " + u.getMax() +
" expected = " + values[MAX]);
}
System.out.println(u);
}
public static Double getMemUsage() {
if ( isLinux() ) {
try {
Double value;
String pid = JavaUtils.process_pid();
String command = String.format("top -b -n 1 -p %s | grep -w %s", pid, pid);
String output = SystemOperation.exec(command);
int m = 0;
String[] strArray = output.split(" ");
for (int i = 0; i < strArray.length; i++) {
String info = strArray[i];
if (info.trim().length() == 0) {
continue;
}
if (m == 5) {
// memory
String unit = info.substring(info.length() - 1);
if (unit.equalsIgnoreCase("g")) {
value = Double.parseDouble(info.substring(0, info.length() - 1));
value *= 1000000000;
} else if (unit.equalsIgnoreCase("m")) {
value = Double.parseDouble(info.substring(0, info.length() - 1));
value *= 1000000;
} else if (unit.equalsIgnoreCase("t")) {
value = Double.parseDouble(info.substring(0, info.length() - 1));
value *= 1000000000000l;
} else {
value = Double.parseDouble(info);
}
// LOG.info("!!!! Get Memory Size:{}, info:{}", value,
// info);
return value;
}
if (m == 8) {
// cpu usage
}
if (m == 9) {
// memory ratio
}
m++;
}
} catch (Exception e) {
LOGGER.warn("Failed to get memory usage", e);
}
}
// this will be incorrect
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
return (double) memoryUsage.getUsed();
}