== Using the SharedData API

As its name suggests, the `link:../../yardoc/Vertx/SharedData.html[SharedData]` API allows you to safely share data between:

- different parts of your application, or
- different applications in the same Vert.x instance, or
- different applications across a cluster of Vert.x instances.

In practice, it provides:

- synchronous maps (local-only)
- asynchronous maps
- asynchronous locks
- asynchronous counters

IMPORTANT: The behavior of the distributed data structure depends on the cluster manager you use.
Backup (replication) and behavior when a network partition is faced are defined by the cluster manager and its configuration.
Please refer to the cluster manager documentation as well as to the underlying framework manual.

=== Local maps

`link:../../yardoc/Vertx/LocalMap.html[Local maps]` allow you to share data safely between different event loops (e.g. different verticles) in the same Vert.x instance.

They only allow certain data types to be used as keys and values:

- immutable types (e.g. strings, booleans, ... etc), or
- types implementing the `link:unavailable[Shareable]` interface (buffers, JSON arrays, JSON objects, or your own shareable objects).

In the latter case the key/value will be copied before putting it into the map.

This way we can ensure there is no _shared access to mutable state_ between different threads in your Vert.x application.
And you won't have to worry about protecting that state by synchronising access to it.

Here's an example of using a shared local map:

[source,ruby]
----
require 'vertx/buffer'
sharedData = vertx.shared_data()

map1 = sharedData.get_local_map("mymap1")

map1.put("foo", "bar")

map2 = sharedData.get_local_map("mymap2")

map2.put("eek", Vertx::Buffer.buffer().append_int(123))

# Then... in another part of your application:

map1 = sharedData.get_local_map("mymap1")

val = map1.get("foo")

map2 = sharedData.get_local_map("mymap2")

buff = map2.get("eek")

----

=== Asynchronous shared maps

`link:../../yardoc/Vertx/AsyncMap.html[Asynchronous shared maps]` allow data to be put in the map and retrieved locally or from any other node.

This makes them really useful for things like storing session state in a farm of servers hosting a Vert.x Web application.

Getting the map is asynchronous and the result is returned to you in the handler that you specify. Here's an example:

[source,ruby]
----
sharedData = vertx.shared_data()

sharedData.get_async_map("mymap") { |res_err,res|
  if (res_err == nil)
    map = res
  else
    # Something went wrong!
  end
}

----

When Vert.x is clustered, data that you put into the map is accessible locally as well as on any of the other cluster members.

IMPORTANT: In clustered mode, asynchronous shared maps rely on distributed data structures provided by the cluster manager.
Beware that the latency relative to asynchronous shared map operations can be much higher in clustered than in local mode.

If your application doesn't need data to be shared with every other node, you can retrieve a local-only map:

[source,ruby]
----
sharedData = vertx.shared_data()

sharedData.get_local_async_map("mymap") { |res_err,res|
  if (res_err == nil)
    # Local-only async map
    map = res
  else
    # Something went wrong!
  end
}

----

==== Putting data in a map

You put data in a map with `link:../../yardoc/Vertx/AsyncMap.html#put-instance_method[put]`.

The actual put is asynchronous and the handler is notified once it is complete:

[source,ruby]
----
map.put("foo", "bar") { |resPut_err,resPut|
  if (resPut_err == nil)
    # Successfully put the value
  else
    # Something went wrong!
  end
}

----

==== Getting data from a map

You get data from a map with `link:../../yardoc/Vertx/AsyncMap.html#get-instance_method[get]`.

The actual get is asynchronous and the handler is notified with the result some time later:

[source,ruby]
----
map.get("foo") { |resGet_err,resGet|
  if (resGet_err == nil)
    # Successfully got the value
    val = resGet
  else
    # Something went wrong!
  end
}

----

===== Other map operations

You can also remove entries from an asynchronous map, clear them and get the size.

See the `link:../../yardoc/Vertx/AsyncMap.html[API docs]` for a detailed list of map operations.

=== Asynchronous locks

`link:../../yardoc/Vertx/Lock.html[Asynchronous locks]` allow you to obtain exclusive locks locally or across the cluster.
This is useful when you want to do something or access a resource on only one node of a cluster at any one time.

Asynchronous locks have an asynchronous API unlike most lock APIs which block the calling thread until the lock is obtained.

To obtain a lock use `link:../../yardoc/Vertx/SharedData.html#get_lock-instance_method[getLock]`.
This won't block, but when the lock is available, the handler will be called with an instance of `link:../../yardoc/Vertx/Lock.html[Lock]`, signalling that you now own the lock.

While you own the lock, no other caller, locally or on the cluster, will be able to obtain the lock.

When you've finished with the lock, you call `link:../../yardoc/Vertx/Lock.html#release-instance_method[release]` to release it, so another caller can obtain it:

[source,ruby]
----
sharedData = vertx.shared_data()

sharedData.get_lock("mylock") { |res_err,res|
  if (res_err == nil)
    # Got the lock!
    lock = res

    # 5 seconds later we release the lock so someone else can get it

    vertx.set_timer(5000) { |tid|
      lock.release()
    }

  else
    # Something went wrong
  end
}

----

You can also get a lock with a timeout. If it fails to obtain the lock within the timeout the handler will be called with a failure:

[source,ruby]
----
sharedData = vertx.shared_data()

sharedData.get_lock_with_timeout("mylock", 10000) { |res_err,res|
  if (res_err == nil)
    # Got the lock!
    lock = res

  else
    # Failed to get lock
  end
}

----

See the `link:../../yardoc/Vertx/Lock.html[API docs]` for a detailed list of lock operations.

IMPORTANT: In clustered mode, asynchronous locks rely on distributed data structures provided by the cluster manager.
Beware that the latency relative to asynchronous shared lock operations can be much higher in clustered than in local mode.

If your application doesn't need the lock to be shared with every other node, you can retrieve a local-only lock:

[source,ruby]
----
sharedData = vertx.shared_data()

sharedData.get_local_lock("mylock") { |res_err,res|
  if (res_err == nil)
    # Local-only lock
    lock = res

    # 5 seconds later we release the lock so someone else can get it

    vertx.set_timer(5000) { |tid|
      lock.release()
    }

  else
    # Something went wrong
  end
}

----

=== Asynchronous counters

It's often useful to maintain an atomic counter locally or across the different nodes of your application.

You can do this with `link:../../yardoc/Vertx/Counter.html[Counter]`.

You obtain an instance with `link:../../yardoc/Vertx/SharedData.html#get_counter-instance_method[getCounter]`:

[source,ruby]
----
sharedData = vertx.shared_data()

sharedData.get_counter("mycounter") { |res_err,res|
  if (res_err == nil)
    counter = res
  else
    # Something went wrong!
  end
}

----

Once you have an instance you can retrieve the current count, atomically increment it, decrement and add a value to
it using the various methods.

See the `link:../../yardoc/Vertx/Counter.html[API docs]` for a detailed list of counter operations.

IMPORTANT: In clustered mode, asynchronous counters rely on distributed data structures provided by the cluster manager.
Beware that the latency relative to asynchronous shared counter operations can be much higher in clustered than in local mode.

If your application doesn't need the counter to be shared with every other node, you can retrieve a local-only counter:

[source,ruby]
----
sharedData = vertx.shared_data()

sharedData.get_local_counter("mycounter") { |res_err,res|
  if (res_err == nil)
    # Local-only counter
    counter = res
  else
    # Something went wrong!
  end
}

----