addMetadata

@CanIgnoreReturnValue()
public static boolean addMetadata<T>(MetadataKey<T> key, T value)

Adds a single metadata key/value pair to the current context.

Warning: It is always better to create a new context via newContext rather than attempting to modify an existing context. In order of preference you should:

  1. Call or wrap a new context with metadata added to it.
  2. install() a new context and close it when you it exits (e.g. if you are using callbacks to listen to state changes in a task). However it is vital that the returned ScopedLoggingContext.LogContextCloseable is always closed.
  3. Call this method and check that it succeeded (e.g. logging a warning if it fails).

Unlike Tags, which have a well defined value ordering, independent of the order in which values were added, context metadata preserves the order of addition. As such, it is not advised to add values for the same metadata key from multiple threads, since that may create non-deterministic ordering. It is recommended (where possible) to add metadata when building a new context, rather than adding it to context visible to multiple threads.