-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathCacheStatus.java
More file actions
250 lines (230 loc) · 9.19 KB
/
Copy pathCacheStatus.java
File metadata and controls
250 lines (230 loc) · 9.19 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package blazingcache.server;
import blazingcache.utils.RawString;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Gestione listeners
*
* @author enrico.olivelli
*/
public class CacheStatus {
private static final Logger LOGGER = Logger.getLogger(CacheStatus.class.getName());
private final Map<RawString, Set<String>> clientsForKey = new HashMap<>();
private final Map<String, Set<RawString>> keysForClient = new HashMap<>();
private final Map<RawString, Long> entryExpireTime = new HashMap<>();
// clientId -> id of the connection that last registered a key for it. Used to make
// the disconnect cleanup connection-identity aware: a late cleanup of a dead
// connection must not wipe the registrations a new connection of the same client made
// after reconnecting. Guarded by {@link #lock}.
private final Map<String, Long> connectionForClient = new HashMap<>();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
@Override
public String toString() {
lock.readLock().lock();
try {
return "CacheListeners{" + "clientsForKey=" + clientsForKey + ", keysForClient=" + keysForClient + '}';
} finally {
lock.readLock().unlock();
}
}
public void registerKeyForClient(RawString key, String client, long connectionId, long expiretime) {
LOGGER.log(Level.FINEST, "registerKeyForClient key={0} client={1} connection={2}", new Object[]{key, client, connectionId});
lock.writeLock().lock();
try {
Set<String> clients = clientsForKey.get(key);
if (clients == null) {
clients = new HashSet<>();
clientsForKey.put(key, clients);
}
clients.add(client);
Set<RawString> keys = keysForClient.get(client);
if (keys == null) {
keys = new HashSet<>();
keysForClient.put(client, keys);
}
keys.add(key);
// record which connection owns this client's registrations now; a later
// disconnect of an older connection will not wipe them (see removeClientListeners).
// Advance the owner FORWARD-ONLY: connection ids are monotonic, so a late
// registration arriving from an older (already-superseded) connection - e.g. a
// delayed fetch reply, or a put/load that was queued behind a held lock - must
// not move ownership back to that dead connection and defeat the guard.
connectionForClient.merge(client, connectionId, Math::max);
if (expiretime > 0) {
entryExpireTime.put(key, expiretime);
} else {
entryExpireTime.remove(key);
}
} finally {
lock.writeLock().unlock();
}
}
public Set<String> getClientsForKey(RawString key) {
lock.readLock().lock();
try {
Set<String> clients = clientsForKey.get(key);
if (clients == null) {
return Collections.emptySet();
} else {
return new HashSet<>(clients);
}
} finally {
lock.readLock().unlock();
}
}
public int getTotalEntryCount() {
lock.readLock().lock();
try {
return clientsForKey.size();
} finally {
lock.readLock().unlock();
}
}
public Set<RawString> getKeys() {
lock.readLock().lock();
try {
return new HashSet<>(clientsForKey.keySet());
} finally {
lock.readLock().unlock();
}
}
public List<RawString> getKeysForClient(String client) {
lock.readLock().lock();
try {
Set<RawString> keys = keysForClient.get(client);
if (keys == null) {
return Collections.emptyList();
} else {
return new ArrayList<>(keys);
}
} finally {
lock.readLock().unlock();
}
}
public void removeKeyForClient(RawString key, String client) {
LOGGER.log(Level.FINEST, "removeKeyForClient key={0} client={1}", new Object[]{key, client});
lock.writeLock().lock();
try {
Set<String> clients = clientsForKey.get(key);
if (clients != null) {
clients.remove(client);
if (clients.isEmpty()) {
clientsForKey.remove(key);
entryExpireTime.remove(key);
}
}
Set<RawString> keys = keysForClient.get(client);
if (keys != null) {
keys.remove(key);
if (keys.isEmpty()) {
keysForClient.remove(client);
connectionForClient.remove(client);
}
}
} finally {
lock.writeLock().unlock();
}
LOGGER.log(Level.FINEST, "removeKeyForClient key={0} client={1} -> keysForClient {2}", new Object[]{key, client, keysForClient});
}
/**
* Removes the key listeners of a disconnected connection, but ONLY if that connection
* is still the one that owns the client's registrations. If a newer connection of the
* same client (a reconnect) has registered in the meantime, this is a no-op so its
* fresh registrations are not wiped — the check and the removal happen atomically
* under the write lock, together with the concurrent registerKeyForClient, so there
* is no time-of-check/time-of-use gap. The dead connection's now-stale registrations
* are then left as benign, self-healing phantoms.
*
* @return the number of listeners removed. Application locks are released separately
* by the {@link KeyedScheduler}, which owns the lock lifecycle.
*/
int removeClientListeners(String clientId, long connectionId) {
AtomicInteger count = new AtomicInteger();
lock.writeLock().lock();
try {
Long owner = connectionForClient.get(clientId);
if (owner != null && owner != connectionId) {
// a newer connection of this client already took over its registrations
return 0;
}
Set<RawString> keys = keysForClient.get(clientId);
if (keys != null) {
keys.forEach((key) -> {
count.incrementAndGet();
Set<String> clients = clientsForKey.get(key);
if (clients != null) {
clients.remove(clientId);
if (clients.isEmpty()) {
clientsForKey.remove(key);
entryExpireTime.remove(key);
}
}
});
}
keysForClient.remove(clientId);
connectionForClient.remove(clientId);
} finally {
lock.writeLock().unlock();
}
return count.get();
}
Set<String> getAllClientsWithListener() {
lock.readLock().lock();
try {
Set<String> clients = keysForClient.keySet();
return new HashSet<>(clients);
} finally {
lock.readLock().unlock();
}
}
List<RawString> selectExpiredEntries(long now, int max) {
lock.readLock().lock();
try {
return entryExpireTime.entrySet().stream().filter(entry -> entry.getValue() < now)
.map(entry -> entry.getKey()).limit(max).collect(Collectors.toList());
} finally {
lock.readLock().unlock();
}
}
void touchKeyFromClient(RawString key, String clientId, long expiretime) {
LOGGER.log(Level.FINEST, "touchKeyFromClient key={0} client={1} expiretime={2}", new Object[]{key, clientId, expiretime});
lock.writeLock().lock();
try {
if (clientsForKey.containsKey(key)) {
if (expiretime > 0) {
entryExpireTime.put(key, expiretime);
} else {
entryExpireTime.remove(key);
}
}
} finally {
lock.writeLock().unlock();
}
}
}