diff --git a/context/src/main/java/io/grpc/Context.java b/context/src/main/java/io/grpc/Context.java index db7aaf7ab9..4de295605a 100644 --- a/context/src/main/java/io/grpc/Context.java +++ b/context/src/main/java/io/grpc/Context.java @@ -330,6 +330,15 @@ public class Context { return new Context(this, new Object[][]{{k1, v1}, {k2, v2}, {k3, v3}}); } + /** + * Create a new context with the given key value set. The new context will cascade cancellation + * from its parent. + */ + public Context withValues(Key k1, V1 v1, Key k2, V2 v2, + Key k3, V3 v3, Key k4, V4 v4) { + return new Context(this, new Object[][]{{k1, v1}, {k2, v2}, {k3, v3}, {k4, v4}}); + } + /** * Create a new context which propagates the values of this context but does not cascade its * cancellation. diff --git a/context/src/test/java/io/grpc/ContextTest.java b/context/src/test/java/io/grpc/ContextTest.java index af80d11eec..a05808e84e 100644 --- a/context/src/test/java/io/grpc/ContextTest.java +++ b/context/src/test/java/io/grpc/ContextTest.java @@ -78,6 +78,7 @@ public class ContextTest { private static final Context.Key FOOD = Context.keyWithDefault("food", "lasagna"); private static final Context.Key COLOR = Context.key("color"); private static final Context.Key FAVORITE = Context.key("favorite"); + private static final Context.Key LUCKY = Context.key("lucky"); private Context listenerNotifedContext; private CountDownLatch deadlineLatch = new CountDownLatch(1); @@ -246,6 +247,23 @@ public class ContextTest { base.attach(); } + @Test + public void withValuesFour() { + Object fav = new Object(); + Context base = Context.current().withValues(PET, "dog", COLOR, "blue"); + Context child = base.withValues(PET, "cat", FOOD, "cheese", FAVORITE, fav, LUCKY, 7); + + child.attach(); + + assertEquals("cat", PET.get()); + assertEquals("cheese", FOOD.get()); + assertEquals("blue", COLOR.get()); + assertEquals(fav, FAVORITE.get()); + assertEquals(7, (int) LUCKY.get()); + + base.attach(); + } + @Test public void cancelReturnsFalseIfAlreadyCancelled() { Context.CancellableContext base = Context.current().withCancellation();