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
|
/*******************************************************************************
* Copyright (c) 2014 Wind River Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.debug.test.util;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.tcf.debug.test.services.ResetMap.IResettable;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.IToken;
/**
*
*/
public abstract class TokenCache<V> extends AbstractCache<V> implements IResettable {
private final IChannel fChannel;
private AtomicReference<IToken> fToken = new AtomicReference<IToken>();
private IChannel.IChannelListener fChannelListener = new IChannel.IChannelListener() {
@Override
public void onChannelClosed(Throwable error) {
if (!isValid()) {
set(null, new IOException("Channel closed.", error), true);
}
}
@Override
public void congestionLevel(int level) {}
@Override
public void onChannelOpened() {}
};
public TokenCache(IChannel channel) {
fChannel = channel;
}
private void addChannelListener() {
fChannel.addChannelListener(fChannelListener);
}
private void removeChannelListener() {
fChannel.removeChannelListener(fChannelListener);
}
@Override
final protected void retrieve() {
IToken previous = fToken.getAndSet(retrieveToken());
if (previous == null) {
addChannelListener();
}
}
protected boolean checkToken(IToken token) {
boolean tokenMatches = fToken.compareAndSet(token, null);
if (tokenMatches) {
removeChannelListener();
}
return tokenMatches;
}
abstract protected IToken retrieveToken();
protected void set(IToken token, V data, Throwable error) {
if (checkToken(token) ) {
set(data, error, true);
}
}
@Override
public void set(V data, Throwable error, boolean valid) {
super.set(data, error, valid);
// If new value was set to the cache but a command is still
// outstanding. Cancel the command.
IToken token = fToken.getAndSet(null);
if (token != null) {
token.cancel();
removeChannelListener();
}
}
@Override
protected void canceled() {
IToken token = fToken.getAndSet(null);
token.cancel();
removeChannelListener();
}
}
|