In addition, the librares also support a range of asynchronous methods that can be used to store, update and retrieve values without having to explicitly wait for a response.
The asynchronous methods use a Future object or its appropriate implementation which is returned by the initial method call for the operation. The communication with the Couchbase server will be handled by the client libraries in the background so that the main program loop can continue. You can recover the status of the operation by using a method to check the status on the returned Future object. For example, rather than synchronously getting a key, an asynchronous call might look like this:
GetFuture getOp = client.asyncGet("someKey");
This will populate the Future object GetFuture
with the response from the server. The Future object class is
defined
here.
The primary methods are:
cancel()
Attempts to Cancel the operation if the operation has not already been completed.
get()
Waits for the operation to complete. Gets the object returned by the operation as if the method was synchronous rather than asynchronous.
get(timeout, TimeUnit)
Gets the object waiting for a maximum time specified by
timeout and the corresponding
TimeUnit.
isDone()
The operation has been completed successfully.
For example, you can use the timeout method to obtain the value or cancel the operation:
GetFuture getOp = client.asyncGet("someKey"); Object myObj; try { myObj = getOp.get(5, TimeUnit.SECONDS); } catch(TimeoutException e) { getOp.cancel(false); }
Alternatively, you can do a blocking wait for the response by
using the get() method:
Object myObj; myObj = getOp.get();