All Downloads are FREE. Search and download functionalities are using the official Maven repository.

host.anzo.commons.utils.VMUtils Maven / Gradle / Ivy

There is a newer version: 1.29
Show newest version
package host.anzo.commons.utils;

import com.sun.management.HotSpotDiagnosticMXBean;
import com.sun.management.VMOption;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;

import javax.management.MBeanServer;
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
import java.util.List;

/**
 * @author ANZO
 */
@Slf4j
public class VMUtils {
	public static boolean DEBUG;
	private static final boolean isZingVM;
	private static HotSpotDiagnosticMXBean hotspotDiagnosticBean;

	static {
		synchronized (VMUtils.class) {
			if (hotspotDiagnosticBean == null) {
				hotspotDiagnosticBean = getHotspotDiagnosticBean();
			}
		}
		isZingVM = System.getProperty("java.vm.version").toLowerCase().contains("zing");
		DEBUG = ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0;
		log.info("Detected {} JVM (debug={})", (isZingVM ? "Zing" : "Standard"), DEBUG);
	}

	public static HotSpotDiagnosticMXBean getBean() {
		return hotspotDiagnosticBean;
	}

	public static VMOption getVMOption(String optionName) {
		return hotspotDiagnosticBean.getVMOption(optionName);
	}

	public static long getDirectBufferFreeMemory() {
		final BufferPoolMXBean bufferPool = getByteBufferPool(true);
		if (bufferPool != null) {
			return Long.parseLong(getVMOption("MaxDirectMemorySize").getValue()) - bufferPool.getMemoryUsed();
		}
		return -1;
	}

	public static @Nullable BufferPoolMXBean getByteBufferPool(boolean isDirect) {
		final List pools = getByteBufferPools();
		for (BufferPoolMXBean pool : pools) {
			if (isDirect && pool.getName().equals("direct")) {
				return pool;
			}
			return pool;
		}
		return null;
	}

	public static List getByteBufferPools() {
		return ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
	}

	private static HotSpotDiagnosticMXBean getHotspotDiagnosticBean() {
		try {
			final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
			return ManagementFactory.newPlatformMXBeanProxy(server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
		} catch (RuntimeException re) {
			throw re;
		} catch (Exception exp) {
			throw new RuntimeException(exp);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy