/** * Create a context reference for a given object with * a given unique id. * * @param obj for which to create a reference * @param cid correlation to be associated with this context reference */ public ContextRef(Object obj, String cid) { this(getObjectRef(obj), cid); }
/** * Obtain a context reference {@link ContextRef} for a specific object and associate it with a specified correlation * id. Context reference is cached until {{@link #clearRef(Object)} is called. Use this method to track object * references across threads within the same JVM. The thread passing object to another thread should call * {@link #getRef(Object)} and the thread that receives object should call {@link #clearRef(Object)}. * * @param obj * object for which context reference is obtained * @param cid * correlation id to be associated with this object * @return context reference associated with the specified object */ public ContextRef getRef(Object obj, String cid) { String refKey = ContextRef.getObjectRef(obj); ContextRef ref = REF_MAP.get(refKey); if (ref == null) { ref = new ContextRef(obj, cid); ContextRef prev = REF_MAP.putIfAbsent(ref.oid(), ref); ref = prev != null ? prev : ref; } return ref; }
/** * Discard a context reference {@link ContextRef} associated with a given object. Context references are created and * cached using {@link #getRef(Object)} and discarded using {@link #clearRef(Object)}. Use this method to track * object references across threads within the same JVM. * * @param obj * object whose reference is discarded * @return context reference associated with the specified object */ public ContextRef clearRef(Object obj) { String refKey = ContextRef.getObjectRef(obj); return REF_MAP.remove(refKey); }