Skip to content

Instantly share code, notes, and snippets.

@zhugw
Created April 12, 2017 01:40
Show Gist options
  • Save zhugw/40b33b075c68bcf9890a8ed747227c63 to your computer and use it in GitHub Desktop.
Save zhugw/40b33b075c68bcf9890a8ed747227c63 to your computer and use it in GitHub Desktop.
MemoryOccupyTest
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by zhuguowei on 4/12/17.
*/
public class MemoryOccupyTest {
@Test
public void test_add_diff_object() throws Exception {
final Runtime runtime = Runtime.getRuntime();
runtime.gc();
Thread.sleep(1000);
final long startMem = runtime.totalMemory() - runtime.freeMemory();
List<Foo> fooList = new ArrayList<>(3);
fooList.add(new Foo());
fooList.add(new Foo());
fooList.add(new Foo());
final long endMem = runtime.totalMemory() - runtime.freeMemory();
long diff = endMem - startMem;
System.out.printf("start: %d end: %d diff: %d",startMem,endMem, diff);
assertTrue(diff > 3*1024*1024);
}
@Test
public void test_add_same_object() throws Exception {
final Runtime runtime = Runtime.getRuntime();
runtime.gc();
Thread.sleep(1000);
final long startMem = runtime.totalMemory() - runtime.freeMemory();
List<Foo> fooList = new ArrayList<>(3);
Foo foo = new Foo();
fooList.add(foo);
fooList.add(foo);
fooList.add(foo);
assertEquals(3, fooList.size());
final long endMem = runtime.totalMemory() - runtime.freeMemory();
long diff = endMem - startMem;
System.out.printf("start: %d end: %d diff: %d",startMem,endMem, diff);
assertTrue(diff < 2*1024*1024);
}
static class Foo{
byte[] padding = new byte[1 * 1024 * 1024];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment