Skip to content

Commit

Permalink
Add ContextMaps to let users create various ContextMaps
Browse files Browse the repository at this point in the history
Motivation:

If we plan to use `ContextMap` for more and more use-cases as a
strictly typed variant of a `Map`, we need to open a way to create
various versions of the `ContextMap`.

Modifications:
- Add `ContextMaps` utility class;
- Add `SingletonContextMap` and `UnmodifiableContextMap`;
- Move `NoopAsyncContextProvider.NoopContextMap` to `EmptyContextMap`;
- Move `ConcurrentContextMap` and `CopyOnWriteContextMap` to context-api;
- Copy `io.servicetalk.concurrent.internal.DefaultContextMap` to
`io.servicetalk.context.api.DefaultContextMap`;
- Deprecate `io.servicetalk.concurrent.internal.DefaultContextMap`;
- Copy `io.servicetalk.concurrent.internal.ContextMapUtils` to
`io.servicetalk.context.api.ContextMapUtils`;
- Deprecate `io.servicetalk.concurrent.internal.ContextMapUtils`;

Result:

New public API to create various `ContextMap`s.
  • Loading branch information
idelpivnitskiy committed May 1, 2024
1 parent 7c85161 commit b69e976
Show file tree
Hide file tree
Showing 17 changed files with 827 additions and 146 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@

import io.servicetalk.context.api.ContextMap;
import io.servicetalk.context.api.ContextMapHolder;
import io.servicetalk.context.api.ContextMaps;

import static java.lang.ThreadLocal.withInitial;

final class AsyncContextMapThreadLocal {
static final ThreadLocal<ContextMap> CONTEXT_THREAD_LOCAL = withInitial(AsyncContextMapThreadLocal::newContextMap);

private static ContextMap newContextMap() {
return new CopyOnWriteContextMap();
return ContextMaps.newCopyOnWriteMap();
}

ContextMap get() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,18 @@
import io.servicetalk.concurrent.CompletableSource;
import io.servicetalk.concurrent.PublisherSource.Subscriber;
import io.servicetalk.concurrent.SingleSource;
import io.servicetalk.concurrent.internal.ContextMapUtils;
import io.servicetalk.context.api.ContextMap;
import io.servicetalk.context.api.ContextMaps;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.annotation.Nullable;

final class NoopAsyncContextProvider implements AsyncContextProvider {
static final AsyncContextProvider INSTANCE = new NoopAsyncContextProvider();
Expand All @@ -43,7 +40,7 @@ private NoopAsyncContextProvider() {

@Override
public ContextMap context() {
return NoopContextMap.INSTANCE;
return ContextMaps.emptyMap();
}

@Override
Expand Down Expand Up @@ -154,121 +151,4 @@ public <T, U, V> BiFunction<T, U, V> wrapBiFunction(final BiFunction<T, U, V> fu
final ContextMap context) {
return func;
}

private static final class NoopContextMap implements ContextMap {
static final ContextMap INSTANCE = new NoopContextMap();

private NoopContextMap() {
// Singleton
}

@Override
public int size() {
return 0;
}

@Override
public boolean isEmpty() {
return true;
}

@Override
public boolean containsKey(final Key<?> key) {
return false;
}

@Override
public boolean containsValue(@Nullable final Object value) {
return false;
}

@Override
public <T> boolean contains(final Key<T> key, @Nullable final T value) {
return false;
}

@Nullable
@Override
public <T> T get(final Key<T> key) {
return null;
}

@Override
public <T> T getOrDefault(final Key<T> key, final T defaultValue) {
return defaultValue;
}

@Nullable
@Override
public <T> T put(final Key<T> key, @Nullable final T value) {
return null;
}

@Nullable
@Override
public <T> T putIfAbsent(final Key<T> key, @Nullable final T value) {
return null;
}

@Nullable
@Override
public <T> T computeIfAbsent(final Key<T> key, final Function<Key<T>, T> computeFunction) {
return null;
}

@Override
public void putAll(final ContextMap map) {
}

@Override
public void putAll(final Map<Key<?>, Object> map) {
}

@Nullable
@Override
public <T> T remove(final Key<T> key) {
return null;
}

@Override
public boolean removeAll(final Iterable<Key<?>> keys) {
return false;
}

@Override
public void clear() {
}

@Nullable
@Override
public Key<?> forEach(final BiPredicate<Key<?>, Object> consumer) {
return null;
}

@Override
public ContextMap copy() {
return this;
}

@Override
public int hashCode() {
return System.identityHashCode(this);
}

@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ContextMap)) {
return false;
}
return ((ContextMap) o).isEmpty();
}

@Override
public String toString() {
return ContextMapUtils.toString(this);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,11 @@

/**
* Shared utilities for {@link ContextMap}.
*
* @deprecated This class will be removed in the future releases.
*/
public final class ContextMapUtils {
@Deprecated
public final class ContextMapUtils { // FIXME: 0.43 - remove deprecated class
private ContextMapUtils() {
// no instances
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package io.servicetalk.concurrent.internal;

import io.servicetalk.context.api.ContextMap;
import io.servicetalk.context.api.ContextMaps;

import java.util.HashMap;
import java.util.Map;
Expand All @@ -29,8 +30,11 @@
* Default implementation of {@link ContextMap}.
* <p>
* Note: it's not thread-safe!
*
* @deprecated Use {@link ContextMaps#newDefaultMap()}.
*/
public final class DefaultContextMap implements ContextMap {
@Deprecated
public final class DefaultContextMap implements ContextMap { // FIXME: 0.43 - remove deprecated class

private final Map<Key<?>, Object> theMap;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.concurrent.api;

import io.servicetalk.concurrent.internal.ContextMapUtils;
import io.servicetalk.context.api.ContextMap;
package io.servicetalk.context.api;

import java.util.Map;
import java.util.Map.Entry;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Copyright © 2021 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.context.api;

import io.servicetalk.context.api.ContextMap.Key;

import javax.annotation.Nullable;

import static java.lang.Integer.toHexString;
import static java.lang.System.identityHashCode;
import static java.util.Objects.requireNonNull;

/**
* Shared utilities for {@link ContextMap}.
*/
final class ContextMapUtils {
private ContextMapUtils() {
// no instances
}

/**
* {@link Object#toString()} implementation for {@link ContextMap}.
*
* @param map {@link ContextMap} to convert
* @return {@link String} representation of the context map
*/
static String toString(final ContextMap map) {
final String simpleName = map.getClass().getSimpleName();
final int size = map.size();
if (size == 0) {
return simpleName + '@' + toHexString(identityHashCode(map)) + ":{}";
}
// 12 is 1 character for '@' + 8 hash code integer in hex form + 1 character for ':' + 2 characters for "{}".
// Assume size of 90 for each key/value pair: 42 overhead characters for formatting + 16 characters for key
// name + 16 characters for key type + 16 characters for value.
StringBuilder sb = new StringBuilder(simpleName.length() + 12 + size * 90);
sb.append(simpleName)
.append('@')
// There are many copies of these maps around, the content maybe equal but a differentiating factor is
// the object reference. this may help folks understand why state is not visible across AsyncContext
// boundaries.
.append(toHexString(identityHashCode(map)))
.append(":{");

map.forEach((key, value) -> {
sb.append(key).append('=').append(value == map ? "(this Map)" : value).append(", ");
return true;
});
sb.setLength(sb.length() - 2);
return sb.append('}').toString();
}

/**
* {@link java.util.Objects#equals(Object, Object)} alternative for {@link ContextMap}.
*
* @param first the first {@link ContextMap}
* @param second the second {@link ContextMap} to compare equality with the first one
* @return {@code true} if both {@link ContextMap}(s) are equal (contains the same elements), {@code false}
* otherwise.
*/
static boolean equals(final ContextMap first, final ContextMap second) {
if (first.size() != second.size()) {
return false;
}
@SuppressWarnings("unchecked")
final Key<?> stopped = first.forEach((key, value) -> second.contains((Key<? super Object>) key, value));
return stopped == null;
}

/**
* Make sure that the {@code value} type matches with the {@link Key#type()}.
*
* @param key the {@link Key} to verify
* @param value the value to verify
* @throws NullPointerException if {@code key == null}
* @throws IllegalArgumentException if type of the {@code value} does not match with {@link Key#type()}
*/
static void ensureType(final Key<?> key, @Nullable final Object value) {
requireNonNull(key);
if (value != null && !key.type().isInstance(value)) {
throw new IllegalArgumentException("Type of the value " + value + '(' + value.getClass() + ')' +
" does mot match with " + key);
}
}
}
Loading

0 comments on commit b69e976

Please sign in to comment.