View difference between Paste ID: ECQpz8g4 and ZbxV1WHM
SHOW: | | - or go back to the newest paste.
1
import java.io.IOException;
2
import java.lang.management.ManagementFactory;
3
import java.util.ArrayList;
4
import java.util.List;
5
import java.util.function.Function;
6
import java.util.function.Supplier;
7
import java.util.stream.IntStream;
8
import com.sun.management.ThreadMXBean;
9
10
11
public class Main {
12-
	private final static ThreadMXBean threadMgmt = getSunThreadMxBean();	// @Nullable to enforce checking (99.99999% to be non-null)
12+
	private final static ThreadMXBean threadMgmt = getSunThreadMxBean();
13
14
	public static long getMemoryAllocated(Thread thread) {
15
		if (threadMgmt == null) {
16
			return -1;
17
		} else {
18
			return threadMgmt.getThreadAllocatedBytes(thread.getId());
19
		}
20
	}
21
22
	private static ThreadMXBean getSunThreadMxBean() {
23
		try {
24
			// original bean is from j.l.m package (interface), but actually it's Sun's extension
25
			return (ThreadMXBean) ManagementFactory.getThreadMXBean();
26
		} catch (ClassCastException fail) {
27
			return null;
28
		}
29
	}
30
31
	public static void main(String[] args) throws IOException, InterruptedException {
32
		Thread.sleep(10_000);
33
		System.out.println(getMemoryAllocated(Thread.currentThread()));
34
		int[] ints = IntStream.range(0, Integer.MAX_VALUE >> 1).toArray();
35
		System.out.println(ints.length);
36
		System.out.println(getMemoryAllocated(Thread.currentThread()));
37
		ints = null;
38
		System.gc();
39
		System.out.println(getMemoryAllocated(Thread.currentThread()));
40
		Thread.sleep(10_000);
41
		String s = "";
42
		for (int i = 0; i < 10_000; i++) {
43
			s += i;
44
		}
45
		System.out.println(getMemoryAllocated(Thread.currentThread()));
46
		System.out.println(s);
47
		System.out.println(getMemoryAllocated(Thread.currentThread()));
48
	}
49
}