1 package com
.google
.apphosting
.api
;
5 import javax
.annotation
.Nullable
;
8 * Holds the current trace context visible to user code. If present, this object will be stored
9 * under the KEY-variable in an Environment's property.
11 * This class is used to share the current trace context between run time and user code. It is not
12 * responsible for managing contexts. It only keeps the most current context for a given thread.
14 public abstract class CloudTrace
{
15 private static final String KEY
= "com.google.apphosting.api.cloudTrace";
17 private static final ThreadLocal
<CloudTraceContext
> perThreadContext
= new ThreadLocal
<>();
20 * Returns the corresponding CloudTrace object for a given environment. If the
21 * environment does not have a CloudTrace object, null will be returned.
24 private static CloudTrace
get(ApiProxy
.Environment env
) {
25 return (CloudTrace
) env
.getAttributes().get(KEY
);
29 * Returns the current trace context for the given environment and the current thread.
30 * @param env the current environment.
33 public static CloudTraceContext
getCurrentContext(ApiProxy
.Environment env
) {
34 CloudTrace cloudTrace
= CloudTrace
.get(env
);
35 return (cloudTrace
== null) ?
null : cloudTrace
.getCurrentContext();
39 * Returns the current trace context for the current thread.
42 private CloudTraceContext
getCurrentContext() {
43 CloudTraceContext context
= perThreadContext
.get();
44 return (context
== null) ?
getDefaultContext() : context
;
48 * Sets the current trace context for the current environment and the current thread.
49 * @param env the current environment.
50 * @param context the current trace context.
52 public static void setCurrentContext(
53 ApiProxy
.Environment env
,
54 @Nullable CloudTraceContext context
) {
55 CloudTrace cloudTrace
= CloudTrace
.get(env
);
56 if (cloudTrace
!= null) {
57 perThreadContext
.set(context
);
62 * Binds this object to a particular environment.
63 * @param env the Environment object to bind this object to.
64 * @throws IllegalStateException if an object is already bound
66 protected void bind(ApiProxy
.Environment env
) {
68 Map
<String
, Object
> attrs
= env
.getAttributes();
70 synchronized (attrs
) {
71 original
= (CloudTrace
) attrs
.get(KEY
);
72 if (original
== null) {
77 if (original
!= this) {
78 throw new IllegalStateException("Cannot replace existing CloudTrace object");
83 * Returns the default context when a thread-specific one doesn't exist.
85 protected abstract CloudTraceContext
getDefaultContext();