package AAAcollect;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.AviatorEvaluatorInstance;
import java.util.HashMap;
import java.util.Map;
// -verbose:class -verbose:gc
// Aviator 是一个轻量级、高性能的 Java 表达式执行引擎, 它动静地将表达式编译成字节码并运行。
// <!– https://mvnrepository.com/art… –>
// <dependency>
// <groupId>com.googlecode.aviator</groupId>
// <artifactId>aviator</artifactId>
// <version>5.2.1</version>
// <version>5.2.7</version>
// </dependency>
public class YxhTest {
private static final AviatorEvaluatorInstance instance = AviatorEvaluator.newInstance();
public static void main(String[] args) throws Exception {Thread.sleep(5000);
instance.importFunctions(YxhService.class);
YxhService yxhService = new YxhService();
for (int i = 0; i < 1900; i++) {Map<String, Object> env = new HashMap<>();
YxhDemo demo = new YxhDemo();
demo.setUid("123");
env.put("demo", demo);
env.put("YxhService", yxhService);
for (int j = 0; j < 128; j++) {instance.execute("a = YxhService.print(YxhService,demo.uid)", env, true);
}
SoftRefTest.doyang();}
Thread.sleep(10000000);
}
}
package AAAcollect;
public class YxhService {
public String print(String str){return str;}
}
package AAAcollect;
public class YxhDemo {
public String getUid() {return uid;}
public void setUid(String uid) {this.uid = uid;}
public String uid;
public String print(String str){return str;}
}
package AAAcollect;
import java.lang.reflect.Method;
// -XX:+UseG1GC
// -XX:+UseConcMarkSweepGC
// -Xloggc:gc.log
// -verbose:class
// -Xms50m -Xmx50m -XX:+UseConcMarkSweepGC -verbose:gc -verbose:class -XX:+PrintGC -XX:SoftRefLRUPolicyMSPerMB=0 -XX:MaxMetaspaceSize=32m
// -Xms50m -Xmx50m -XX:+UseG1GC -verbose:gc -verbose:class -XX:+PrintGC -XX:SoftRefLRUPolicyMSPerMB=0
public class SoftRefTest {
public static void main(String[] args) throws Exception {Thread.sleep(5000);
for (int t = 0; t < 35000; t++) {// 触发 yanggc
// doyang();
// doyang();
new SoftRefTest().doso();
// 触发 yanggc
// doyang();
// 触发 yanggc
doyang();
// doyang();}
}
public static void doyang() {for (int ct = 0; ct < 6000; ct++) {byte[] bytes = new byte[1024 * 10];
for (int i = 0; i < bytes.length; i++) {bytes[i] = '1';
}
}
}
public static void doso() throws Exception {Class<?> clz = Class.forName("MethodAccessor.A");
Object o = clz.newInstance();
Method m = clz.getMethod("foo", String.class);
for (int i = 0; i < 20; i++) {m.invoke(o, "");
}
}
}
package AAAcollect;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
// 元空间有余,间接扩容,如果扩容到 MetaspaceSize 引发 old gc(依据垃圾回收器决定),卸载类并扩容
// 扩容到 MaxMetaspaceSize,引发 full gc 卸载类。
public class SerializeConfigTest {
public static String buildData(Object bean) {
try {
// 每次 new 一个 Config 会导致每次生成一个序列化类,// 而后用不同的类加载器加载进来,导致暂用元空间的内存
SerializeConfig CONFIG = new SerializeConfig();
JSON.toJSONString(bean, CONFIG);
return "";
} catch (Exception e) {return null;}
}
// -XX:MaxMetaspaceSize=40m -Xms50m -Xmx50m -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:CMSInitiatingOccupancyFraction=50 -XX:+UseCMSInitiatingOccupancyOnly -XX:+UseConcMarkSweepGC
public static void main(String[] args) throws Exception {System.out.println("======================================");
Thread.sleep(3000);
int i = 0;
while (i < 900000) {buildData(new SerializeConfigTest());
i++;
}
System.out.println("===============================================");
Thread.sleep(1000000000);
}
}
package AAAcollect;
import MethodAccessor.WeakRefTest;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import static java.lang.invoke.MethodHandles.lookup;
// -XX:+UnlockDiagnosticVMOptions -Xms50m -Xmx50m -verbose:class -verbose:gc
// -XX:+ShowHiddenFrames -Djava.lang.invoke.MethodHandle.DUMP_CLASS_FILES=true
// 同一个 methodHandle 对象调用 127 次后都会加载一个新的类,同一个办法的不同 methodHandler 对象不共用次数
public class MHTest {
class GrandFather {void thinking() {System.out.println("i am grandfather");
}
String talk(String s) {// System.out.println("i am grandfather talk");
return s;
}
}
class Father extends GrandFather {void thinking() {
// new Exception().printStackTrace();
}
String talk(String s) {if (s.equals("1") || s.equals("127")) {new Exception().printStackTrace();}
return s;
}
}
class Son extends Father {void thinking() {System.out.println("i am son");
}
}
public void showMt(MethodHandle mh) throws Throwable {Field field = MethodHandle.class.getDeclaredField("asTypeCache");
Field field2 = MethodHandle.class.getDeclaredField("customizationCount");
field.setAccessible(true);
field2.setAccessible(true);
MethodHandle mhCache = (MethodHandle) field.get(mh);
System.out.println(field2.get(mhCache));
}
public void dododo() throws Throwable {for (int i = 0; i < 128; i++) {MethodType mt = MethodType.methodType(String.class, String.class);
MethodHandle mh = lookup().findVirtual(GrandFather.class, "talk", mt)
.bindTo(new MHTest().new Father());
mh.invoke("" + i);
showMt(mh);
}
}
public static void main(String[] args) {
try {Thread.sleep(3000);
for (int i = 0; i < 10000; i++) {Thread.sleep(5000);
new MHTest().dododo();
System.out.println("================");
}
} catch (Throwable e) {e.printStackTrace();
}
}
}
package AAAcollect;
import sun.nio.ch.Util;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MapFileOperateTest {
public static void main(String[] args) throws Exception {File file = new File("D:\\Users\\YEZHENGWU839\\Desktop\\test.txt");
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
FileChannel fileChannel =
new RandomAccessFile(file, "rw")
.getChannel();
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, file.length());
mappedByteBuffer.put((byte) 54);
mappedByteBuffer.put((byte) 59);
mappedByteBuffer.put((byte) 60);
// 强制刷盘
mappedByteBuffer.force();
System.out.println(mappedByteBuffer.get(0));
System.out.println(mappedByteBuffer.get(1));
System.out.println(mappedByteBuffer.get(2));
// 用 threadLocal 做了缓存
ByteBuffer byteBuffer = Util.getTemporaryDirectBuffer(20);
for (int i = 0; i < 10; i++) {byteBuffer.put((byte) 53);
}
byteBuffer.flip();
// 从那个地位开始写
fileChannel.write(byteBuffer,3);
System.out.println();
System.out.println(mappedByteBuffer.get(0));
System.out.println(mappedByteBuffer.get(1));
System.out.println(mappedByteBuffer.get(2));
fileChannel.force(true);
fileChannel.read(buffer,3);
buffer = null;
System.gc();
Util.releaseTemporaryDirectBuffer(byteBuffer);
Thread.sleep(300000);
}
}
package AAAcollect;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.util.List;
// -XX:MaxMetaspaceSize=200M -XX:MetaspaceSize=50M -XX:+UseG1GC
public class JvmMeans {
public static void main(String[] args) throws Exception {show();
}
public static void show() throws Exception {MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
List<MemoryPoolMXBean> memoryPoolMXBeanList = ManagementFactory.getMemoryPoolMXBeans();
// 该信息提供了大量的信息。在 JVM 中,可能有几个内存池,因而有对应的内存池信息,因而,在工厂类中
//,getMemoryPoolMXBean() 失去是一个 MemoryPoolMXBean 的 list。每一个 MemoryPoolMXBean 都蕴含
long s = memoryPoolMXBeanList.get(1).getUsage().getMax();
System.out.println(s);
// 了该内存池的详细信息,如是否可用、以后已应用内存 / 最大应用内存值、以及设置最大内存值等等。for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeanList) {
// 内存池的名称
String poolName = memoryPoolMXBean.getName();
// 内存管理器的名称
long committed = memoryPoolMXBean.getUsage().getCommitted();
long max = memoryPoolMXBean.getUsage().getMax();
long used = memoryPoolMXBean.getUsage().getUsed();
long init = memoryPoolMXBean.getUsage().getInit();
System.out.println("name" + poolName + "\r\nmax" + max + "committed" + committed + "used" + used + "init" + init);
}
ObjectName directName = new ObjectName("java.nio:type=BufferPool,name=direct");
ObjectName mappedName = new ObjectName("java.nio:type=BufferPool,name=mapped");
MBeanInfo directInfo = mbs.getMBeanInfo(directName);
for (MBeanAttributeInfo i : directInfo.getAttributes()) {System.out.println(i.getName() + ":" + mbs.getAttribute(directName, i.getName()));
}
MBeanInfo mappedInfo = mbs.getMBeanInfo(mappedName);
for (MBeanAttributeInfo i : mappedInfo.getAttributes()) {System.out.println(i.getName() + ":" + mbs.getAttribute(mappedName, i.getName()));
}
}
}
package AAAcollect;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class ConcurrentWeakInternSet<T> {
private final ConcurrentMap<WeakEntry<T>, WeakEntry<T>> map;
private final ReferenceQueue<T> stale;
public ConcurrentWeakInternSet() {this.map = new ConcurrentHashMap<>();
this.stale = new ReferenceQueue<>();}
public T get(T elem) {if (elem == null) throw new NullPointerException();
expungeStaleElements();
WeakEntry<T> value = map.get(new WeakEntry<>(elem));
if (value != null) {T res = value.get();
if (res != null) {return res;}
}
return null;
}
public T add(T elem) {if (elem == null) throw new NullPointerException();
// Playing double race here, and so spinloop is required.
// First race is with two concurrent updaters.
// Second race is with GC purging weak ref under our feet.
// Hopefully, we almost always end up with a single pass.
T interned;
WeakEntry<T> e = new WeakEntry<>(elem, stale);
do {expungeStaleElements();
WeakEntry<T> exist = map.putIfAbsent(e, e);
interned = (exist == null) ? elem : exist.get();} while (interned == null);
return interned;
}
private void expungeStaleElements() {
Reference<? extends T> reference;
while ((reference = stale.poll()) != null) {map.remove(reference);
}
}
public ConcurrentMap<WeakEntry<T>, WeakEntry<T>> getMap() {return map;}
private static class WeakEntry<T> extends WeakReference<T> {
public final int hashcode;
public WeakEntry(T key, ReferenceQueue<T> queue) {super(key, queue);
hashcode = key.hashCode();}
public WeakEntry(T key) {super(key);
hashcode = key.hashCode();}
@Override
public boolean equals(Object obj) {if (obj instanceof WeakEntry) {Object that = ((WeakEntry) obj).get();
Object mine = get();
return (that == null || mine == null) ? (this == obj) : mine.equals(that);
}
return false;
}
@Override
public int hashCode() {return hashcode;}
}
}
package AAAcollect;
import MethodAccessor.A;
import sun.misc.Unsafe;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
/**
- defineAnonymousClass jvm 定义匿名类
*/
// -XX:MaxMetaspaceSize=40M -XX:MetaspaceSize=32M -verbose:class -XX:MaxMetaspaceSize=40M -XX:MetaspaceSize=32M -verbose:class -XX:MaxMetaspaceSize=40M -XX:MetaspaceSize=32M -verbose:class -XX:+UseG1GC -verbose:gc -XX:+PrintGC
// -XX:+UnlockCommercialFeatures
// -XX:+FlightRecorder
// -XX:StartFlightRecording=delay=20s,duration=60s,filename=D:\myRecording.jfr,settings=default
// https://blog.csdn.net/dnc8371…
// https://blog.csdn.net/maosiju…
public class AnonymousClassTest {
public static void main(String args[]) throws Throwable {Thread.sleep(4000);
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
String filePath = "D:\\soft\\untitled\\target\\classes\\MethodAccessor\\Aa.class";
byte[] buffer = getBytesFromFile(filePath);
Class<?> c1 = unsafe.defineAnonymousClass(A.class, buffer, null);
System.out.println(c1.getName() + " " + c1.getClassLoader());
for (int i = 0; i < 40000; i++) {c1 = unsafe.defineAnonymousClass(A.class, buffer, null);
Thread.sleep(1);
}
// Thread.sleep(1000000);
}
public static byte[] getBytesFromFile(String fileName) {
try {
// precondition
File file = new File(fileName);
InputStream is = new FileInputStream(file);
long length = file.length();
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {offset += numRead;}
if (offset < bytes.length) {
throw new IOException("Could not completely read file"
+ file.getName());
}
is.close();
return bytes;
} catch (Exception e) {
System.out.println("error occurs in _ClassTransformer!"
+ e.getClass().getName());
return null;
}
}
}