Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Второй случай является более правильным, поскольку в большинстве случаев это явно укажет сборщику на сбор неиспользванного экземпляра первоначально созданного HeavyElem.
static class Foo {
byte[] b = new byte[32*1024*1024];
}
public static void main(String[] args) throws Exception {
for(int i = 0; i < 3; i++) {
Foo f = new Foo();
}
}
public class TestMem {
public static void main(String[] args) throws Exception {
System.err.println("create 1");
Test2 e = new Test2();
e = null;
System.err.println("create 2");
e = new Test2();
}
public static class Test2 {
private char mas[] = new char[50000000];
}
}e = null;
System.gc();
System.gc();
String автор = ВойнаИМир.substring(12).
static class Foo {
static int sequence;
int id = ++sequence;
@Override
public int hashCode() {
// return id;
return ++sequence;
}
}
public static void main(String[] args) throws Exception {
HashSet<Foo> foos = new HashSet<Foo>();
Foo foo = new Foo();
foos.add(foo);
System.out.println(foos.remove(foo));
System.out.println(foos.size());
}
false 1
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
} // Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}class Leak {
static Leak instance;
Leak() {
instance = this;
throw new Error();
}
}
class Leak {
static Leak instance;
{
instance = this;
throw new Error();
}
}
Типичные случаи утечки памяти в Java