Skip to content

Commit bbefacc

Browse files
authored
All things were made by him
All things were made by him; and without him was not any thing made that was made. (John 1:3)
1 parent 7f4a97b commit bbefacc

1 file changed

Lines changed: 105 additions & 0 deletions

File tree

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
2+
//All things were made by him; and without him was not any thing made that was made. (John 1:3)
3+
4+
package com.javarush.task.task34.task3405;
5+
6+
import java.lang.ref.SoftReference;
7+
import java.util.ArrayList;
8+
import java.util.List;
9+
10+
/*
11+
Мягкие ссылки
12+
*/
13+
public class Solution {
14+
public static Helper helper = new Helper();
15+
16+
public static class Monkey {
17+
private String name;
18+
19+
public Monkey(String name) {
20+
this.name = name;
21+
}
22+
23+
protected void finalize() {
24+
Helper.isFinalized = true;
25+
System.out.format("Bye-Bye, %s!\n", name);
26+
}
27+
}
28+
29+
public static void main(String args[]) throws InterruptedException {
30+
helper.startTime();
31+
32+
Monkey monkey = new Monkey("Simka");
33+
34+
SoftReference <Monkey> reference = new SoftReference<Monkey>(monkey);//Add reference here
35+
36+
helper.callGC();
37+
38+
monkey = null;
39+
40+
helper.callGC();
41+
helper.heapConsuming();
42+
43+
if (reference.get() == null)
44+
System.out.println("Finalized");
45+
46+
helper.finish();
47+
}
48+
49+
public static class Helper {
50+
public static boolean isFinalized;
51+
52+
private long startTime;
53+
54+
void startTime() {
55+
this.startTime = System.currentTimeMillis();
56+
}
57+
58+
int getTime() {
59+
return (int) (System.currentTimeMillis() - startTime) / 1000;
60+
}
61+
62+
void callGC() throws InterruptedException {
63+
System.gc();
64+
Thread.sleep(1000);
65+
}
66+
67+
void heapConsuming() {
68+
try {
69+
List<Solution> heap = new ArrayList<Solution>(100000);
70+
while (!isFinalized) {
71+
heap.add(new Solution());
72+
}
73+
} catch (OutOfMemoryError e) {
74+
System.out.println("Out of memory error raised");
75+
}
76+
}
77+
78+
public void finish() {
79+
System.out.println("Done");
80+
System.out.println("It took " + getTime() + " sec");
81+
}
82+
}
83+
}
84+
85+
/*
86+
Мягкие ссылки
87+
88+
Разберись в примере.
89+
90+
Внутри метода main после создания объекта типа Monkey создай мягкую ссылку (SoftReference) на него.
91+
92+
93+
94+
95+
96+
Требования:
97+
98+
1. В методе main должен быть создан объект типа Monkey с именем "Simka".
99+
100+
2. В методе main должен быть создан SoftReference на объект monkey.
101+
102+
3. Класс Monkey должен быть публичным.
103+
104+
4. Класс Monkey должен быть статическим.
105+
*/

0 commit comments

Comments
 (0)