下面列出了io.netty.util.Attribute#compareAndSet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public <T> T getAttribute(final String key, final Function<String, T> function) {
if (key == null) {
return null;
}
Attribute<T> attribute = channel.attr(AttributeKey.valueOf(key));
T result = attribute.get();
if (result == null && function != null) {
T target = function.apply(key);
if (target != null) {
if (attribute.compareAndSet(null, target)) {
return target;
} else {
return attribute.get();
}
}
}
return result;
}
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) {
Attribute<Span> spanAttr = ctx.channel().attr(NettyHttpTracing.SPAN_ATTRIBUTE);
Span span = spanAttr.get();
spanAttr.compareAndSet(span, null);
if (span == null || !(msg instanceof HttpResponse)) {
ctx.write(msg, prm);
return;
}
HttpResponse response = (HttpResponse) msg;
Scope scope = currentTraceContext.maybeScope(span.context());
Throwable error = null;
try {
ctx.write(msg, prm);
} catch (Throwable t) {
error = t;
throw t;
} finally {
HttpServerRequest request = ctx.channel().attr(NettyHttpTracing.REQUEST_ATTRIBUTE).get();
handler.handleSend(new HttpResponseWrapper(request, response, error), span);
scope.close();
}
}
public void put(UUID recId, ChannelHandlerContext ctx) {
if(ctx == null) {
return;
}
Attribute<UUID> recIdAttr = ctx.attr(REC_KEY);
if(!recIdAttr.compareAndSet(null, recId)) {
throw new IllegalStateException("attempt to set existing non-null ctx recId [" + recIdAttr.get() + "] to [" + recId + "]");
}
sessions.put(recIdAttr.get(), ctx);
}
public static ChannelTransport getOrNewTransport(Channel channel, RequestBarrier requestBarrier) {
Attribute<ChannelTransport> attr = channel.attr(TRANSPORT_CACHE_ATTR);
ChannelTransport transport = attr.get();
if (transport == null) {
transport = newTransport(channel, requestBarrier);
if (!attr.compareAndSet(null, transport)) {
transport = attr.get();
}
}
return transport;
}
/**
* 添加新的会话
* @param channel
* @param session
* @return
*/
public static boolean addChannelSession(Channel channel, IdSession session) {
Attribute<IdSession> sessionAttr = channel.attr(SESSION_KEY);
return sessionAttr.compareAndSet(null, session);
}