Sometimes it makes sense to allow different verticles instances to share data in a safe way. Vert.x allows simple
SharedMap (like a
SharedSet data structures to be shared between
There is a caveat: To prevent issues due to mutable data, Vert.x only allows simple immutable types such as number, boolean and string or Buffer to be used in shared data. With a Buffer, it is automatically copied when retrieved from the shared data, so different verticle instances never see the same object instance.
Currently data can only be shared between verticles in the same Vert.x instance. In later versions of Vert.x we aim to extend this to allow data to be shared by all Vert.x instances in the cluster.
To use a shared map to share data between verticles first we get a reference to the map, and then use it like
any other instance of
SharedMap<String, Integer> map = vertx.sharedData.getMap("demo.mymap"); map.put("some-key", 123);
And then, in a different verticle you can access it:
SharedMap<String, Integer> map = vertx.sharedData.getMap("demo.mymap"); // etc
To use a shared set to share data between verticles first we get a reference to the set.
SharedSet<String> set = vertx.sharedData.getSet("demo.myset"); set.add("some-value");
And then, in a different verticle:
SharedSet<String> set = vertx.sharedData.getSet("demo.myset"); // etc
A shared map, this class does not use
SharedMap has very similar semantics as ConcurrentMap with the difference that any updates made to the collections returned from keySet, valueSet and entrySet methods do not change the keys and values in the underlying Map.
This is because the Map can contain mutable data such as Buffer and byte objects so we must copy such elements before they are returned to you. This prevents a situation where the same entry entry is being updated concurrently by more than one thread, which could lead to race conditions.
A shared set, this class does not use
Sometimes it is desirable to share immutable data between different event loops, for example to implement a cache of data.
This class allows instances of shared data structures to be looked up and used from different event loops.
The data structures themselves will only allow certain data types to be stored into them. This shields you from worrying about any thread safety issues might occur if mutable objects were shared between event loops.
The following types can be stored in a shareddata data structure:
Instances of this class are thread-safe.