package com.javarush.task.task34.task3407;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;
/*
ÐÑизÑаÑнÑе ÑÑÑлки
РазбеÑиÑÑ Ð² пÑимеÑе.
РеализÑй Ð»Ð¾Ð³Ð¸ÐºÑ Ð¼ÐµÑода getFilledList клаÑÑа Helper:
1) Ñоздай ÑпиÑок, коÑоÑÑй ÑÐ¼Ð¾Ð¶ÐµÑ Ñ
ÑаниÑÑ Ð¿ÑизÑаÑнÑе ÑÑÑлки на обÑекÑÑ Monkey
2) Ð´Ð¾Ð±Ð°Ð²Ñ Ð² ÑпиÑок 200 ÑÑÑлок, иÑполÑзÑйÑе оÑеÑÐµÐ´Ñ helper.getQueue()
3) веÑни заполненнÑй ÑпиÑок
ТÑебованиÑ:
1.âÐеÑод getFilledList должен возвÑаÑаÑÑ ÑпиÑок заполненнÑй ÑанÑомнÑми ÑÑÑлками на обÑекÑÑ Ñипа Monkey.
2.âÐеÑод getFilledList должен возвÑаÑаÑÑ ÑпиÑок из 200 ÑлеменÑов.
3.âÐлаÑÑ Helper не должен бÑÑÑ Ð¿ÑиваÑнÑм.
4.âÐеÑод getFilledList не должен бÑÑÑ Ð¿ÑиваÑнÑм.*/
public class Solution {
public static Helper helper = new Helper();
public static class Monkey {
}
public static void main(String args[]) throws InterruptedException {
helper.startTime();
List> list = helper.getFilledList();
//before GC
helper.checkListWithReferences(list, "before");
helper.callGC();
helper.heapConsuming();
//after GC
helper.checkListWithReferences(list, "after");
helper.finish();
}
public static class Helper {
private ReferenceQueue queue = new ReferenceQueue<>();
private long startTime;
void startTime() {
this.startTime = System.currentTimeMillis();
}
int getTime() {
return (int) (System.currentTimeMillis() - startTime) / 1000;
}
void callGC() throws InterruptedException {
System.gc();
Thread.sleep(1000);
}
public ReferenceQueue getQueue() {
return queue;
}
void heapConsuming() {
try {
List heap = new ArrayList(100000);
while (true) {
heap.add(new Solution());
}
} catch (OutOfMemoryError e) {
System.out.println("Out of memory error raised");
}
}
public void checkListWithReferences(List> list, String string) {
int count = 0;
for (PhantomReference reference : list) {
if (reference.isEnqueued()) {
count++;
}
}
System.out.println(String.format("The enqueue reference count is %d (%s GC was called)", count, string));
}
public List> getFilledList() {
ArrayList> result = new ArrayList<>();
for(int i=0; i<200; i++){
Monkey monkey = new Monkey();
result.add(new PhantomReference<>(monkey, getQueue()));
}
return result;
}
public void finish() throws InterruptedException {
int count = 0;
while (queue.poll() != null) {
count++;
}
System.out.println(count + " objects are in the queue of phantom reference");
System.out.println("It took " + getTime() + " sec");
}
}
}