forked from jbloch/effective-java-3e-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
66 lines (54 loc) · 1.7 KB
/
Copy pathStack.java
File metadata and controls
66 lines (54 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package effectivejava.chapter2.item7;
import java.util.*;
// Can you spot the "memory leak"? (Pages 26-27)
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
return elements[--size];
}
/**
* Ensure space for at least one more element, roughly
* doubling the capacity each time the array needs to grow.
*/
private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
// Corrected version of pop method (Page 27)
// public Object pop() {
// if (size == 0)
// throw new EmptyStackException();
// Object result = elements[--size];
// elements[size] = null; // Eliminate obsolete reference
// return result;
// }
public static void main(String[] args) throws InterruptedException {
Stack stack = new Stack();
System.out.println("push");
//for (String arg : args)
for(int i=0;i< 0x02ffffff ;i++)
stack.push(String.valueOf(i));
Thread.sleep(10000);
System.out.println("pop");
int sleepPeriod = 10000;
int counter = 0;
while (true) {
stack.pop();
counter++;
if(counter % sleepPeriod == 0)
Thread.sleep(100);
}
//System.err.println(stack.pop());
}
}