1
2
3
4
5
6
7
8
9
10
11
12
13 package org.abstracthorizon.mercury.maildir.file;
14
15 import java.io.IOException;
16 import java.util.HashSet;
17 import java.util.Iterator;
18 import java.util.Set;
19
20 import javax.mail.internet.SharedInputStream;
21
22
23
24
25
26
27
28
29 public class SharedInputStreamPool {
30
31
32 protected static SharedInputStreamPool defaultInstance = new SharedInputStreamPool();
33
34
35 protected Set<SharedInputStream> files = new HashSet<SharedInputStream>();
36
37
38 protected int maxFiles = 200;
39
40
41 protected int timeout = 1000;
42
43
44
45
46 public SharedInputStreamPool() {
47 }
48
49
50
51
52
53 public static SharedInputStreamPool getDefaultInstance() {
54 return defaultInstance;
55 }
56
57
58
59
60
61
62
63
64
65 public SharedInputStreamImpl newStream(FileProvider fileProvider, long start, long len) {
66 return new SharedInputStreamImpl(this, fileProvider, start, len);
67 }
68
69
70
71
72
73
74
75
76
77 protected synchronized void opened(SharedInputStreamImpl stream) {
78 files.add(stream);
79 int size = files.size();
80 if (size > maxFiles) {
81 int removed = 0;
82 int timeout = this.timeout * (size/maxFiles) * 2;
83 Iterator<SharedInputStream> it = files.iterator();
84 long now = System.currentTimeMillis();
85 SharedInputStreamImpl oldest = stream;
86 SharedInputStreamImpl s = null;
87 while (it.hasNext()) {
88 s = (SharedInputStreamImpl)it.next();
89 if ((now - stream.lastAccessed) < timeout) {
90 try {
91 s.closeImpl();
92 } catch (IOException ignore) {
93 }
94 it.remove();
95 removed++;
96 } else if ((removed == 0) && (s.lastAccessed <= oldest.lastAccessed)) {
97 oldest = stream;
98 }
99 }
100 if (removed == 0) {
101 closed(oldest);
102 }
103 }
104 }
105
106
107
108
109
110
111
112
113
114 protected synchronized void closed(SharedInputStreamImpl stream) {
115 files.remove(stream);
116 }
117
118
119
120
121
122
123 public synchronized void closeWithProvider(FileProvider provider) {
124 Iterator<SharedInputStream> it = files.iterator();
125 SharedInputStreamImpl s = null;
126 while (it.hasNext()) {
127 s = (SharedInputStreamImpl)it.next();
128 if (s.fileProvider == provider) {
129 try {
130 s.closeImpl();
131 } catch (IOException ignore) {
132 }
133 it.remove();
134 }
135 }
136 }
137 }