From c023d5136725981f7bd54153b945ed615a738167 Mon Sep 17 00:00:00 2001 From: Konrad `ktoso` Malawski Date: Tue, 30 Jan 2018 23:20:15 +0900 Subject: [PATCH] =doc #24435 copy mutable maps before sharing them as messages in java (#24447) * =doc #24435 copy mutable maps before sharing them as messages in java * fix rename * Update DeviceGroup.java * Update DeviceGroup.java --- akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroup.java | 8 +++++++- akka-docs/src/test/java/jdocs/tutorial_6/DeviceGroup.java | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroup.java b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroup.java index d0e54c4e72..9ba4b1f6ea 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroup.java +++ b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroup.java @@ -139,8 +139,14 @@ public class DeviceGroup extends AbstractActor { //#query-added private void onAllTemperatures(RequestAllTemperatures r) { + // since Java collections are mutable, we want to avoid sharing them between actors (since multiple Actors (threads) + // modifying the same mutable data-structure is not safe), and perform a defensive copy of the mutable map: + // + // Feel free to use your favourite immutable data-structures library with Akka in Java applications! + Map actorToDeviceIdCopy = new HashMap<>(this.actorToDeviceId); + getContext().actorOf(DeviceGroupQuery.props( - actorToDeviceId, r.requestId, getSender(), new FiniteDuration(3, TimeUnit.SECONDS))); + actorToDeviceIdCopy, r.requestId, getSender(), new FiniteDuration(3, TimeUnit.SECONDS))); } @Override diff --git a/akka-docs/src/test/java/jdocs/tutorial_6/DeviceGroup.java b/akka-docs/src/test/java/jdocs/tutorial_6/DeviceGroup.java index eed2161331..dfe856f5dd 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_6/DeviceGroup.java +++ b/akka-docs/src/test/java/jdocs/tutorial_6/DeviceGroup.java @@ -133,8 +133,14 @@ public class DeviceGroup extends AbstractActor { } private void onAllTemperatures(RequestAllTemperatures r) { + // since Java collections are mutable, we want to avoid sharing them between actors (since multiple Actors (threads) + // modifying the same mutable data-structure is not safe), and perform a defensive copy of the mutable map: + // + // Feel free to use your favourite immutable data-structures library with Akka in Java applications! + Map actorToDeviceIdCopy = new HashMap<>(this.actorToDeviceId); + getContext().actorOf(DeviceGroupQuery.props( - actorToDeviceId, r.requestId, getSender(), new FiniteDuration(3, TimeUnit.SECONDS))); + actorToDeviceIdCopy, r.requestId, getSender(), new FiniteDuration(3, TimeUnit.SECONDS))); } @Override