0

I am currently trying to implement the Java web service(Rest API) where the endpoint creates the device in the IoTHub and updates the device twin.

There are two methods available in the azure-iot sdk. One is

addDevice(deviceId, authenticationtype)

and another is to

addDeviceAsync(deviceId, authenticationtype)

I just wanted to figure out which one should I use in the web service(as a best practice). I am not very strong in MultiThreading/Concurrency so was wondering to receive people's expertise on this. Any suggestion/Link related to this is much appreciated

Thanks.

Jasmine
  • 135
  • 3
  • 16

1 Answers1

0

The Async version of AddDevice is basically the same. If you use AddDeviceAsync then a thread is created to run the AddDevice call so you are not blocked on it.

Check the code#L269 of RegistryManager doing exactly that: https://github.com/Azure/azure-iot-sdk-java/blob/master/service/iot-service-client/src/main/java/com/microsoft/azure/sdk/iot/service/RegistryManager.java#L269

public CompletableFuture<Device> addDeviceAsync(Device device) throws IOException, IotHubException
{
    if (device == null)
    {
        throw new IllegalArgumentException("device cannot be null");
    }

    final CompletableFuture<Device> future = new CompletableFuture<>();
    executor.submit(() ->
    {
        try
        {
            Device responseDevice = addDevice(device);
            future.complete(responseDevice);
        }
        catch (IOException | IotHubException e)
        {
            future.completeExceptionally(e);
        }
    });
    return future;
}

You can as well build your own async wrapper and call AddDevice() from there.

asergaz
  • 996
  • 5
  • 17