These are the docs for 11.0, an old version of SpatialOS. The docs for this version are frozen: we do not correct, update or republish them. 14.5 is the newest →

The Java worker SDK is currently experimental. We’re very open to feedback — don’t hesitate to get in touch on the forums.

Java worker API

The Java worker API closely mirrors the C# worker API. The full API reference is available as in-code documentation.


The most important units of functionality in the Java worker API are:

  • The improbable.worker.Locator, which is responsible for querying for and connecting to remote cloud deployments.
  • The improbable.worker.Connection, which represents a worker’s connection to a SpatialOS simulated world.
  • The improbable.worker.Dispatcher, which is responsible for invoking user-provided callbacks based on data received from SpatialOS via the improbable.worker.Connection.
  • The improbable.worker.Entity, which is a container for the component data associated with a single entity.

Connecting to SpatialOS

Before it can interact with the simulated world, the worker must connect to SpatialOS.

There are two ways of doing this:

  • Instantiate a improbable.worker.Connection object directly. This allows to connect a managed worker (i.e running in the cloud and started by the SpatialOS runtime) or a remote worker used for debugging via ([spatial cloud connect external](/reference/11.0/tools/spatial/spatial-cloud-connect-external)). The connection is made through the receptionist service of the targeted deployment for which the IP and port should be passed as arguments to the worker. These values can be filled-in automatically at runtime by using the IMPROBABLE_RECEPTIONIST_HOST and IMPROBABLE_RECEPTIONIST_PORT placeholders in your worker’s launch configuration.
  • Use the improbable.worker.Locator object to enumerate cloud deployments and connect to a chosen deployment with authentication. This is typically used to connect an external client to a cloud deployment.

The value given for the useExternalIp field in the NetworkParameters structure is also relevant. The table below summarizes the connection possibilities:

Using improbable.worker.Connection directly Using improbable.worker.Locator
useExternalIp == true Local client connecting via spatial cloud connect external proxy External client connecting to cloud deployment
useExternalIp == false Managed cloud worker; local client connecting to local deployment

The example below illustrates a very basic connection setup, where the worker takes three command-line arguments specifying the worker’s own ID as well as the receptionist’s IP and port. It will use TCP and connect using the internal IP address.

import improbable.worker.*;

public class MyJavaWorker {
  public static void main(String[] args) {
    if (args.length != 3) {

    ConnectionParameters parameters = new ConnectionParameters();
    parameters.workerType = "MyJavaWorker";
    parameters.networkParameters.type = NetworkConnectionType.Tcp;
    parameters.networkParameters.useExternalIp = false;

    String workerId = args[0];
    String hostname = args[1];
    int port = Integer.parseInt(args[2]);

    try (Connection connection = Connection.connectAsync(hostname, port, workerId, parameters).get()) {
      // ...
    } catch (IOException e) {

Note that improbable.worker.Connection objects are not thread-safe.

Handling data received from SpatialOS

It is up to each worker to decide how the basic event loop should be structured, depending on its requirements. The worker should call improbable.worker.Connection.getOpList to get a list of “operations” (for example a new entity, or a component update) from SpatialOS that have been sent since the last time the function was called. This improbable.worker.OpList then needs to be passed to a dispatcher in order to invoke user-provided callbacks.

In order to detect that a worker is still responsive, SpatialOS sends periodic heartbeat requests. Responding to these happens automatically, but the buffer for incoming operations can fill up with other messages. If that happens, the heartbeats cannot be processed and your worker may be killed. Therefore, you should never wait multiple seconds between calls to

The following snippet shows a (very) simple example implementation of an event loop that processes operations from SpatialOS 60 times per second:

public static final int millisecondsPerFrame = 1000 / 60;

void runEventLoop(improbable.worker.Connection connection,
                  improbable.worker.Dispatcher dispatcher)
        throws InterruptedException {
  while (true) {
    try (OpList opList = connection.getOpList(0 /* non-blocking */)) {
      // Invoke user-provided callbacks.
      // Do other work here...

If positive timeout (in milliseconds) is provided to getOpList, the function will block until there is at least one operation to return, or until the timout has been exceeded.

Note that all callbacks provided to the improbable.worker.Dispatcher will be invoked only when improbable.worker.Dispatcher.process is called, and only on the thread that is currently calling improbable.worker.Dispatcher.process: the user has complete control over callback timing and threading decisions.

If the connection fails (when Connection.isConnected() == false), any error messages explaining the cause will be returned by getOpList(). Make sure to process this list in order to receive all available diagnostic information.

Dispatcher callbacks

Several kinds of callbacks can be registered on the improbable.worker.Dispatcher. Each method takes a Callback<Param>, where the parameter type Param depends on the particular kind of callback being registered. The following table has the details:

Method Parameter type (and fields) Invoked when…
onDisconnect improbable.worker.Ops.Disconnect (String reason) the Connection is no longer connected and can no longer be used. Check the log for errors relating to the disconnection.
onLogMessage improbable.worker.Ops.LogMessage (improbable.worker.LogLevel level, String message) the SDK issues a log message for the worker to print. This does not include messages sent using Connection.sendLogMessage.
onMetrics improbable.worker.Ops.Metrics (improbable.worker.Metrics metrics) the SDK reports built-in internal metrics.
onCriticalSection improbable.worker.Ops.CriticalSection (bool inCriticalSection) a critical section is about to be entered or has just been left.
onAddEntity improbable.worker.Ops.AddEntity (improbable.worker.EntityId entityId) an entity is added to the worker’s view of the simulation.
onRemoveEntity improbable.worker.Ops.RemoveEntity (improbable.worker.EntityId entityId) an entity is removed from the worker’s view of the simulation.
onReserveEntityIdResponse improbable.worker.Ops.ReserveEntityIdResponse (improbable.worker.RequestId<ReserveEntityIdRequest> requestId, improbable.worker.StatusCode statusCode, String message, improbable.collection.Option<improbable.worker.EntityId> entityId) the worker has received a response for an entity ID reservation it had requested previously.
onCreateEntityResponse improbable.worker.Ops.CreateEntityResponse (improbable.worker.RequestId<CreateEntityRequest> requestId, improbable.worker.StatusCode statusCode, String message, improbable.collection.Option<improbable.worker.EntityId> entityId) the worker has received a response for an entity creation it had requested previously.
onDeleteEntityResponse improbable.worker.Ops.DeleteEntityResponse (improbable.worker.RequestId<DeleteEntityRequest> requestId, improbable.worker.EntityId entityId, improbable.worker.StatusCode statusCode, String message) the worker has received a response for an entity deletion it had requested previously.
onEntityQueryResponse improbable.worker.Ops.EntityQueryResponse (improbable.worker.RequestId<EntityQueryRequest> requestId, improbable.worker.StatusCode statusCode, String message, int resultCount, Map<improbable.worker.EntityId, improbable.worker.Entity> result) the worker has received a response for an entity query it had requested previously.
onAddComponent<C> improbable.worker.Ops.AddComponent<C> (improbable.worker.EntityId entityId, improbable.worker.IComponentData<C> data) a component is added to an existing entity in the worker’s view of the simulation.
onRemoveComponent<C> improbable.worker.Ops.RemoveComponent (improbable.worker.EntityId entityId) a component is removed from an existing entity in the worker’s view of the simulation.
onAuthorityChange<C> improbable.worker.Ops.AuthorityChange (improbable.worker.EntityId entityId, bool hasAuthority) the worker is granted authority over an entity’s component, or the worker’s authority over an entity’s component is revoked.
onComponentUpdate<C> improbable.worker.Ops.ComponentUpdate<C> (improbable.worker.EntityId entityId, improbable.worker.IComponentUpdate<C> update) a component for an entity in the worker’s view of the simulation has been updated.
onCommandRequest<C> improbable.worker.Ops.CommandRequest<C> (improbable.worker.RequestId<IncomingCommandRequest> requestId, improbable.worker.EntityId entityId, int timeoutMillis, String callerWorkerId, List<String> callerAttributeSet, improbable.worker.CommandRequest<C> request) the worker has received a command request for a component on an entity over which it has authority.
onCommandResponse<C> improbable.worker.Ops.CommandResponse<C> (improbable.worker.RequestId<OutgoingCommandRequest> requestId, improbable.worker.EntityId entityId, improbable.worker.StatusCode statusCode, improbable.collection.Option<improbable.worker.CommandResponse<C>> response) the worker has received a command response for a request it issued previously.

Here’s an example of registering callbacks:

void registerCallbacks(improbable.worker.Dispatcher dispatcher) {
    dispatcher.onAddEntity(op -> {
        // Do something with op.entityId

If you want to unregister a callback, call removeCallback() with the long returned from the registration method:

void registerAndUnregisterCallbacks(improbable.worker.Dispatcher dispatcher) {
    long key = dispatcher.onAddEntity(op -> {
        // Do something with op.entityId

    // ...


Using the View

improbable.worker.View is subclass of improbable.worker.Dispatcher, which adds the functionality of automatically maintaining the current state of the worker’s view of the simulated world. It has a field called entities, which is a map from entity ID to improbable.worker.Entity objects. When a View processes an OpList, it automatically updates the state of this map as appropriate. Any user-defined callbacks are also invoked, as per the Dispatcher contract.

Dispatcher invocation order

Ops.AddEntity callbacks are invoked in the order they were registered with the improbable.worker.Dispatcher, while Ops.RemoveEntity callbacks are invoked in reverse order. This means that pairs of add/remove callbacks can correctly depend on resources managed by pairs of callbacks registered earlier. This is similar to the usual construction/destruction order found in C++, for example. Similarly, Ops.AuthorityChange callbacks are invoked in the order they were registered when authority is granted, but in reverse order when authority is revoked.

Critical sections

The protocol supports the concept of critical sections. A critical section is a block of operations that should be processed atomically by the worker. For example, a set of entities representing a stack of cubes should be added to the scene in its entirety before any physics simulation is done. Note that this notion of a critical section does not provide any guarantees.

The Ops.CriticalSection callback is invoked with inCriticalSection == true just before the first operation of the critical section is delivered, and is invoked again with inCriticalSection == false just after the last operation of the critical section is delivered.

Worker flags

To access the value of a worker flag, use the getWorkerFlag method of a Connection:

Option<String> getWorkerFlag(String flagName)

For example:

Option<String> workSpeedFlag = connection.getWorkerFlag("mycompany_theproject_work_speed");
if (workSpeedFlag.isPresent()) {
} else {

Sending data to SpatialOS

A worker can send data such as logging, metrics, and component updates to SpatialOS using the improbable.worker.Connection.

Logging and metrics

The improbable.worker.Connection has two methods to send diagnostic information to SpatialOS: sendLogMessage, which is used for distributed logging, and sendMetrics, which updates timeseries and histogram data associated with this worker. Logs and metrics are available on deployment dashboards.

The Connection periodically reports several built-in internal metrics using Ops.Metrics, which you would usually want to send to SpatialOS along with your custom metrics. It might look something like this:

improbable.worker.Metrics metrics = new improbable.worker.Metrics();
metrics.gaugeMetrics.put("MyCustomMetric", new Double(1.0));
dispatcher.onMetrics(op -> {
  // Send back the SDK built-in metrics.
  // Send back the user-defined metrics.

Metrics should also be used to set the worker load when using dynamic load balancing for a worker. The load of a worker is a floating-point value, with 0 indicating an unloaded worker and values above 1 corresponding to an overloaded worker. The reported values direct SpatialOS’s load balancing strategy. An example of load reporting could be:

improbable.worker.Metrics metrics = new improbable.worker.Metrics()
Queue<Task> task_queue = new LinkedList<Task>();
double maximum_queue_size = 200;

dispatcher.onMetrics(op -> {
  // Send back the SDK built-in metrics.

  // Update the load metric and send it to SpatialOS.
  metrics.load = new Double(task_queue.size() / maximum_queue_size);

while (true) {
  // Process tasks from the taskQueue.

Sending and receiving component updates

When the worker has authority over a particular component for some entity, it can send component updates to SpatialOS. This is done using the improbable.worker.Connection method sendComponentUpdate, which takes an EntityId instance and an instance of appropriate update class defined in the schema-generated code. The update classes are always called Update and are defined as a static nested classes of each implementation of ComponentMetaclass. For example, if we want to update a component MyComponent, the appropriate update class is nested in it and can by accessed as MyComponent.Update.

A component update can modify the value of a property or trigger an event. You can modify multiple properties and trigger multiple events in the same component update.

Component updates sent by the worker will appear in the operation list returned by a subsequent call to improbable.worker.Connection.getOpList. This means that Ops.ComponentUpdate callbacks will also be invoked for component updates triggered by the worker itself, but not immediately.

There are a couple of (related) reasons that callbacks for sent component updates should not be invoked immediately: this can lead to extremely unintuitive control flow when components are recursively updated inside a callback; it violates the guarantee that callbacks are only invoked as a result of a call to the process method on the improbable.worker.Dispatcher.

To be notified when a worker receives a component update on an entity in the worker’s local view of the simulation, use the improbable.worker.Dispatcher method onComponentUpdate with the same ComponentMetaclass as for sending updates. Note that the component updates can be partial, i.e. only update some properties of the component, do not necessarily have to contain data that is different from the workers current view of the component, and could have been sent by SpatialOS rather than a worker for synchronization purposes.

Sending and receiving component events

Sending and receiving events works much in the same way as component updates. For a schema like the following,

type SwitchToggled {
  int64 time = 1;

component Switch {
  id = 1234;
  bool is_enabled = 1;
  event SwitchToggled toggled;

triggering an event can be done as follows:

Switch.Update update = new Switch.Update();
update.addToggled(new SwitchToggled(1));
connection.sendComponentUpdate(entityId, update);

If you are not authoritative on the component, your event will be silently ignored.

Receiving an event works just like receiving a component update, by registering a callback on the dispatcher:

dispatcher.onComponentUpdate(Switch.class, op -> {
  Switch.Update update = op.update;
  // `update.getToggled()` contains a list of SwitchToggled events.

Sending component interests

For each entity in its view, a worker receives updates for a set of the entity’s components. This set is the union of the set of components the worker has authority over, and a set of components it is explicitly interested in.

The initial set of explicitly interested components can be configured in the bridge settings. This is the default set of explicit interest for every entity. At runtime, the worker can override this set on a per-entity basis, by using the Connection.sendComponentInterest method.

Whenever the set of interested components for an entity changes, the worker will receive the appropriate onAddComponent and onRemoveComponent callbacks to reflect this change.

For example, you might be interested in the local player’s inventory, but not the inventories of other players within the world:

dispatcher.onAuthorityChange(PlayerControls.class, op -> {
  // If we have authority over this player's controls component, then the entity represents the local player.
  if (op.hasAuthority) {
    // A list of components required to visualize the player.
    Map<Integer, InterestOverride> interestOverrides = new HashMap<>();
    interestOverrides.put(Inventory.COMPONENT_ID, new InterestOverride(/* isInterested */ true));
    connection.sendComponentInterest(op.entityId, interestOverrides);

Note that a worker is always considered to be interested in the components of the entities it is authoritative on, in addition to any others specificed in the bridge settings or using the method described above.

Sending and receiving component commands

To send a command to be executed by the worker currently authoritative over a particular component for a particular entity, use the improbable.worker.Connection method sendCommandRequest. This function takes a Class<C> instance, an entity ID, a request object, an optional timeout and an optional CommandParameters object. The C type needs to be a subclass of CommandMetaclass defined in the schema-generated code, and the _request object_ needs has to be of the same type as defined in schema for given commandC. TheCommandParametersobject contains a field called AllowShortCircuiting`, which if set to true will try to “short-circuit” the command and avoid a round trip to SpatialOS in some cases. See documentation on commands for more information.

Before sending the command, a callback to handle the response should be registered with the improbable.worker.Dispatcher with onCommandResponse(Class<C>). The request ID (of type improbable.worker.RequestId<OutgoingCommandRequest>) returned by sendCommandRequest can be matched up with the one in the improbable.worker.Ops.CommandResponse to identify the request that is being responded to.

Note that commands may fail, so the improbable.worker.StatusCode field in the improbable.worker.Ops.CommandResponse should be checked, and the command can be retried as necessary. The caller will always get a response callback, but it can be one of several failure cases, including:

  • ApplicationError (rejected by the target worker or by SpatialOS)
  • AuthorityLost (target worker lost authority, or no worker had authority)
  • NotFound (target entity, or target component on the entity, didn’t exist)
  • PermissionDenied (sending worker didn’t have permission to send request)
  • Timeout
  • InternalError (most likely indicates a bug in SpatialOS, should be reported)

To handle commands issued by another worker, the opposite flow is used. Register a callback with the improbable.worker.Dispatcher with onCommandRequest(Class<C>); when the callback is executed, the worker should make sure to call the improbable.worker.Connection method sendCommandResponse, supplying the request ID (of type improbable.worker.RequestId<IncomingCommandRequest>) provided by the improbable.worker.Ops.CommandRequest and an appropriate response object, matching the response type defined in the schema. Alternatively, the worker can call sendCommandFailure to fail the command instead.

Entity queries

Note: In order to send an entity query, a worker must have permission to do so. For more information, see the Worker permissions page.

A worker can run remote entity queries against the simulation by using the improbable.worker.Connection method sendEntityQueryRequest. This takes an improbable.worker.Query.EntityQuery object and an optional timeout.

The query object is made of an improbable.worker.Query.Constraint and an improbable.worker.Query.ResultType. The constraint determines which entities are matched by the query, and the result type determines what data is returned for matched entities. Available constraints and result types are described below.

Constraint Description
EntityIdConstraint Matches a specific entity ID.
ComponentConstraint Matches entities with a particular component.
SphereConstraint Matches entities contained in the given sphere.
AndConstraint Matches entities that match all of the given subconstraints.
OrConstraint Matches entities that match any of the given subconstraints.
Result type Description
CountResultType Returns the number of entities that matched the query.
SnapshotResultType Returns a snapshot of component data for entities that matched the query. To select all components, use new SnapshotResultType(). To select every component whose ID is contained in the given set, use new SnapshotResultType(componentIdSet) (thus, pass an empty set to get no components but entity IDs only).

Important: You should keep entity queries as limited as possible. All queries hit the network and cause a runtime lookup, which is expensive even in the best cases. This means you should:

  • always limit queries to a specific sphere of the world
  • only return the information you need from queries (eg the specific components you care about)
  • if you’re looking for entities that are within your worker’s checkout radius, search internally on the worker instead of using a query

Like other request methods, this returns an improbable.worker.RequestId request ID, which can be used to match a request with its response. The response is received via a callback registered with the improbable.worker.Dispatcher using the onEntityQueryResponse method.

The Ops.EntityQueryResponse contains an int resultCount field (for CountResultType requests) and a Map<EntityId, Entity> (for SnapshotResultType) requests. Again, success or failure of the request is indicated by the statusCode field of the response object, but in the failure case the result may still contain some data: the count or snapshot map might still contain the data for some entities that matched the query, but won’t necessarily contain all matching entities. This is because the worker might still be able to do something useful with a partial result.

Creating and deleting entities

Note: In order to create or delete an entity, a worker must have permission to do so. For more information, see the Worker permissions page.

A worker can request SpatialOS to reserve an entity ID, create an entity, or delete an entity, by using the improbable.worker.Connection methods sendReserveEntityIdRequest, sendCreateEntityRequest, and sendDeleteEntityRequest, respectively.

These methods return an improbable.worker.RequestId<C> request ID, which can be used to match a request with its response. The type parameter C depends on the type of request being sent. The response is received via a callback registered with the improbable.worker.Dispatcher using onReserveEntityIdResponse, onCreateEntityResponse, and onDeleteEntityResponse, respectively.

Note that these operations may fail, so the statusCode field in the worker.Ops.ReserveEntityId, worker.Ops.CreateEntityResponse, or worker.Ops.DeleteEntityResponse argument of the respective callback should be checked, and the command can be retried as necessary. The caller will always get a response callback, but it might be due to a timeout.

sendReserveEntityIdRequest takes an optional timeout. If the operation succeeds, the response contains an entity ID, which is guaranteed to be unused in the current deployment.

sendCreateEntityRequest takes a improbable.worker.Entity representing the initial state of the entity, an optional entity ID (which, if provided, must have been obtained by a previous call to sendReserveEntityIdRequest), and an optional timeout. If the operation succeeds, the response contains the ID of the newly created entity.

sendDeleteEntityRequest takes an entity ID and an optional timeout. The response contains no additional data.


Here’s an example of reserving an entity ID, creating an entity with that ID and some initial state, and finally deleting it:

final int timeoutMillis = 500;

class RequestIds {
  private RequestId<CreateEntityRequest> entityCreationRequest;
  private RequestId<DeleteEntityRequest> entityDeletionRequest;
final RequestIds requestIds = new RequestIds();

// Reserve an entity ID.
RequestId<ReserveEntityIdRequest> entityIdReservationRequestId = connection.sendReserveEntityIdRequest(Option.of(timeoutMillis));

// When the reservation succeeds, create an entity with the reserved ID.
dispatcher.onReserveEntityIdResponse(op -> {
  if (op.requestId == entityIdReservationRequestId && op.statusCode == StatusCode.SUCCESS) {
    Entity entity = new Entity();
    // Empty ACL - should be customised.
    entity.add(EntityAcl.class, new EntityAclData(new WorkerRequirementSet(new ArrayList<>()), new HashMap<>()));
    // Needed for the entity to be persisted in snapshots.
    entity.add(Persistence.class, new PersistenceData());
    entity.add(Position.class, new PositionData(new Coordinates(1, 2, 3)));
    requestIds.entityCreationRequest = connection.sendCreateEntityRequest(entity, op.entityId, Option.of(timeoutMillis));

// When the creation succeeds, delete the entity.
dispatcher.onCreateEntityResponse(op -> {
  if (op.requestId == requestIds.entityCreationRequest && op.statusCode == StatusCode.SUCCESS) {
    requestIds.entityDeletionRequest = connection.sendDeleteEntityRequest(op.entityId.get(), Option.of(timeoutMillis));

// When the deletion succeeds, we're done.
dispatcher.onDeleteEntityResponse(op -> {
  if (op.requestId == requestIds.entityDeletionRequest && op.statusCode == StatusCode.SUCCESS) {
    // Test successful!

Entity ACLs

Entity ACLs are exposed to the worker as a component, and can be manipulated as any other component. ACLs can be set at entity creation time, or modified dynamically at runtime by the worker that has authority over the EntityAcl component.

This example adds an EntityAcl to an Entity given a CommandRequestOp, which is currently the only way to make a specific worker (as opposed to, potentially, a set of workers) to qualify for authority of a component. Specifically:

  • The entity will be visible to workers that have the “client” or “physics” worker attribute.
  • Any “physics” worker (i.e. a worker with “physics” as one of its attributes) can be authoritative over the entity’s Position and EntityAcl components.
  • The worker, which issued the Ops.CommandRequest, is the only worker that can be authoritative over the PlayerControls component.

This can be used as part of creating a new entity in response to a command request.

void addComponentDelegations(Ops.CommandRequest<?, ?> op, Entity entity)
    // This requirement set matches only the command caller, i.e. the worker that issued the command,
    // since the attribute set includes the caller's unique attribute.
    WorkerAttributeSet callerWorkerAttributeSet = new WorkerAttributeSet(op.callerAttributeSet);
    WorkerRequirementSet callerWorkerRequirementSet = new WorkerRequirementSet(Collections.singletonList(callerWorkerAttributeSet));

    // Worker attribute set of a physics worker
    WorkerAttributeSet physicsWorkerAttributeSet = new WorkerAttributeSet(Collections.singletonList("physics"));
    // Worker attribute set of a client worker
    WorkerAttributeSet clientWorkerAttributeSet = new WorkerAttributeSet(Collections.singletonList("client"));

    // This requirement set matches any worker with the attribute "physics".
    WorkerRequirementSet physicsWorkerRequirementSet = new WorkerRequirementSet(Collections.singletonList(physicsWorkerAttributeSet));

    // This requirement set matches any worker with the attribute "client" or "physics".
    List<WorkerAttributeSet> clientOrPhysicsAttributeSets = new LinkedList<WorkerAttributeSet>();

    WorkerRequirementSet clientOrPhysicsRequirementSet = new WorkerRequirementSet(clientOrPhysicsAttributeSets);

    // Give authority over Position and EntityAcl to any physics worker, and over PlayerControls to the caller worker.
    Map<Integer, WorkerRequirementSet> componentAcl = new HashMap<>();
    componentAcl.put(Position.COMPONENT_ID, physicsWorkerRequirementSet);
    componentAcl.put(EntityAcl.COMPONENT_ID, physicsWorkerRequirementSet);
    componentAcl.put(PlayerControls.COMPONENT_ID, callerWorkerRequirementSet);

    entity.add(EntityAcl.class, new EntityAclData(/* read */ clientOrPhysicsRequirementSet, /* write */ componentAcl));

The worker authoritative over the EntityAcl component can later decide to give the authority over position (or any other component) to a different worker, e.g. the client. In order to do this, EntityAclData needs to be modified in order to map Position.COMPONENT_ID to callerWorkerRequirementSet (created above). This change can be made using the method below:

EntityAclData delegateComponent(EntityAclData currentAcl, Integer componentId, WorkerRequirementSet requirementSet)
    // Take a deep copy, so that this does not modify the current EntityAcl.
    EntityAclData newAcl = currentAcl.deepCopy();
    // Set the write ACL for the specified component to the specified attribute set,
    // assuming the componentAcl option is not empty.
    newAcl.getComponentWriteAcl().put(componentId, requirementSet);
    return newAcl;

For these changes to take effect, the worker authoritative over the EntityAcl component needs send the changes through a component update.

Please read Worker attributes and worker requirement sets for more information.

Generated code

The Java schema-generated code consists of two main parts: data classes and component classes. Data classes are used to represent data at rest and correspond to the schemalang type definitions; component classes correspond to schemalang component definitions and contain metadata and classes for sending and receiving component data (updates, command requests and command responses).

A data class will be generated for each type defined in the schema, with fields corresponding to each field in the schema definition.

For each component, we generate:

  • a metaclass implementing improbable.worker.ComponentMetaclass. These metaclasses are used when referring to specific components when using the API - every generic type parameter C expects a metaclass argument.
  • an Update class nested inside the metaclass. This has an optional field for each field in the component (since it represents a diff).
  • command Request and Response classes nested inside the metaclass. These have an optional field for each command defined by the component (using the request type and response type of the command respectively); however, only one field can be set at a time. Note that the behaviour of responding to a command request using the response field for a different command is undefined.

Data representation

  • Strings are represented as UTF-8 encoded String members. Make sure to use this same encoding when updating a component.
  • list<T> fields are represented as a java.util.List<T> of the repeated type.
  • map<Key, Value> fields are represented as java.util.Map<Key, Value>.
  • option<T> fields are represented as improbable.collections.Option<T>.


Consider the following simple schema:

package example;

type StatusEffect {
  string name = 1;
  int32 multiplier = 2;

component Creature {
  id = 12345;
  int32 health = 1;
  list<StatusEffect> effects = 2;

The generated code will contain the Creature ComponentMetaclass with Data and and Update classes. Moreover, there will be a StatusEffect struct representing the StatusEffect type, and CreatureData type for the (auto-generated) underlying type of the component.

Here are some ways that these classes can be used with the API:

import example.*;
import improbable.worker.*;

public class Example {
  void examples(Connection connection) {
    try (Dispatcher dispatcher = new Dispatcher()) {
      dispatcher.onAuthorityChange(Creature.class, op -> {
        if (op.hasAuthority) {
          // We were granted authority over the status component. Send an update.
          Creature.Update update = new Creature.Update();
          connection.sendComponentUpdate(op.entityId, update);
        } else {
          // Authority was revoked.

      dispatcher.onComponentUpdate(Creature.class, op -> {
        // Again, use the extension method Get() to get the concrete type of update.
        Creature.Update update = op.update;
        if (update.getEffects().isPresent()) {
          // The `effects` field was updated.
  } catch (IOException e) {


The SDK provides two methods in the improbable.worker.Snapshot class to manipulate snapshots stored in files:

 * Load a snapshot from a file. Returns an error message if an error occurred.
 * @param path           The path to the snapshot file.
 * @param entitiesOutput A map which this method will use to store loaded entities.
 * @return An option which will be set to an error string if an error occurred.
public static Option<String> load(String path, /*out*/ final Map<EntityId, Entity> entitiesOutput);

 * Save a snapshot to a file. Returns an error message if an error occurred.
 * @param path     The path to the snapshot file.
 * @param entities A map containing entities which will be saved to this snapshot.
 * @return An option which will be set to an error string if an error occurred.
public static Option<String> save(String path, Map<EntityId, Entity> entities);

Note that, unlike the rest of the API described in this document, snapshot manipulation does not require a Connection, making it possible to develop standalone, offline snapshot manipulation tools. However, we recommend using the build infrastructure provided by SpatialOS for workers to build your standalone tools.

Here is an example of loading a snapshot, performing some manipulation on it, and saving it back. It uses the types and components defined in the example above.

import example.Creature;
import example.CreatureData;
import example.StatusEffect;
import improbable.collections.Option;
import improbable.worker.Entity;
import improbable.worker.EntityId;
import improbable.worker.Snapshot;

public class SnapshotExample {
  void addLowHealthEffectToEntities(String snapshotFilename) {
    // Load a snapshot from a file.
    Map<EntityId, Entity> entities = new HashMap<EntityId, Entity>();
    Option<String> errorOpt = Snapshot.load(snapshotFilename, entities);
    if (errorOpt.isPresent()) {
      throw new RuntimeException("Error loading snapshot: " + errorOpt.get());

    // Add the "LowHealth" effect to all entities that have a Creature component and less than 10 health points.
    for (Map.Entry<EntityId, Entity> pair : entities.entrySet()) {
      Entity entity = pair.getValue();
      if (entity.get(Creature.class).isPresent()) {
        CreatureData status = entity.get(Creature.class).get();
        if (status.getHealth() < 10) {
          status.getEffects().add(new StatusEffect("LowHealth", 100));

    // Save the snapshot back to the file.
    errorOpt =, entities);
    if (errorOpt.isPresent()) {
      throw new RuntimeException("Error saving snapshot: " + errorOpt.get());

Search results

Was this page helpful?

Thanks for letting us know!

Thanks for your feedback

Need more help? Ask on the forums