1 package cz.cuni.amis.utils.objectmanager;
2
3 import java.lang.ref.SoftReference;
4 import java.util.LinkedList;
5 import java.util.Queue;
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 public class ObjectManager<MANAGED_OBJECT> {
31
32
33
34
35 private Queue<SoftReference<MANAGED_OBJECT>> freeObjects;
36
37
38
39
40 private IObjectFactory<MANAGED_OBJECT> objectFactory;
41
42
43
44
45
46 private int moreNewObjectsCount;
47
48 public ObjectManager(IObjectFactory<MANAGED_OBJECT> objectFactory) {
49 this(objectFactory, 10, 5);
50 }
51
52
53
54
55
56 public ObjectManager(IObjectFactory<MANAGED_OBJECT> objectFactory, int initialObjectCount) {
57 this(objectFactory, initialObjectCount, 5);
58 }
59
60
61
62
63
64
65 public ObjectManager(IObjectFactory<MANAGED_OBJECT> objectFactory, int initialObjectCount, int moreNewObjectsCount) {
66
67 if (moreNewObjectsCount <= 0) moreNewObjectsCount = 1;
68
69 this.moreNewObjectsCount = moreNewObjectsCount;
70
71 this.objectFactory = objectFactory;
72
73 freeObjects = new LinkedList<SoftReference<MANAGED_OBJECT>>();
74
75 generateNewObjects(initialObjectCount);
76 }
77
78
79
80
81
82 private void generateNewObjects(int count) {
83 for (int i = 0; i < count; ++i) {
84 freeObjects.add(new SoftReference<MANAGED_OBJECT>(objectFactory.newObject()));
85 }
86 }
87
88
89
90
91
92 public MANAGED_OBJECT get() {
93 synchronized(freeObjects) {
94 if (freeObjects.size() == 0) generateNewObjects(moreNewObjectsCount);
95 SoftReference<MANAGED_OBJECT> reference = freeObjects.poll();
96 MANAGED_OBJECT obj = reference.get();
97 while (obj == null && freeObjects.size() > 0) {
98 reference = freeObjects.poll();
99 obj = reference.get();
100 }
101 if (obj != null) return obj;
102 return objectFactory.newObject();
103 }
104 }
105
106
107
108
109
110
111
112
113
114 public void giveBack(MANAGED_OBJECT obj) {
115 synchronized(freeObjects) {
116 freeObjects.add(new SoftReference<MANAGED_OBJECT>(obj));
117 }
118 }
119
120 }