Example usage for com.google.common.util.concurrent SettableFuture create

List of usage examples for com.google.common.util.concurrent SettableFuture create

Introduction

In this page you can find the example usage for com.google.common.util.concurrent SettableFuture create.

Prototype

public static <V> SettableFuture<V> create() 

Source Link

Document

Creates a new SettableFuture that can be completed or cancelled by a later method call.

Usage

From source file:org.apache.omid.tso.client.MockTSOClient.java

@Override
public TSOFuture<Long> commit(long transactionId, Set<? extends CellId> cells) {
    synchronized (conflictMap) {
        SettableFuture<Long> f = SettableFuture.create();
        if (transactionId < lwm.get()) {
            f.setException(new AbortException());
            return new ForwardingTSOFuture<>(f);
        }// www. j ava  2  s .c  o m

        boolean canCommit = true;
        for (CellId c : cells) {
            int index = Math.abs((int) (c.getCellId() % CONFLICT_MAP_SIZE));
            if (conflictMap[index] >= transactionId) {
                canCommit = false;
                break;
            }
        }

        if (canCommit) {
            long commitTimestamp = timestampGenerator.incrementAndGet();
            for (CellId c : cells) {
                int index = Math.abs((int) (c.getCellId() % CONFLICT_MAP_SIZE));
                long oldVal = conflictMap[index];
                conflictMap[index] = commitTimestamp;
                long curLwm = lwm.get();
                while (oldVal > curLwm) {
                    if (lwm.compareAndSet(curLwm, oldVal)) {
                        break;
                    }
                    curLwm = lwm.get();
                }
            }

            f.set(commitTimestamp);
            try {
                commitTable.addCommittedTransaction(transactionId, commitTimestamp);
                commitTable.updateLowWatermark(lwm.get());
                commitTable.flush();
            } catch (IOException ioe) {
                f.setException(ioe);
            }
        } else {
            f.setException(new AbortException());
        }
        return new ForwardingTSOFuture<>(f);
    }
}

From source file:org.opendaylight.controller.md.sal.dom.broker.impl.DOMNotificationRouterEvent.java

ListenableFuture<Void> initialize(final DOMNotification notification,
        final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers) {
    this.notification = Preconditions.checkNotNull(notification);
    this.subscribers = Preconditions.checkNotNull(subscribers);
    this.future = SettableFuture.create();
    return this.future;
}

From source file:org.anhonesteffort.p25.chnlzr.ChnlzrConnectionFactory.java

public ListenableFuture<ChnlzrConnectionHandler> create(HostId chnlzrHost) {
    SettableFuture<ChnlzrConnectionHandler> future = SettableFuture.create();
    ChnlzrConnectionHandler connection = new ChnlzrConnectionHandler(future);
    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(workerGroup).channel(channel).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectionTimeoutMs())
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, config.bufferHighWaterMark())
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, config.bufferLowWaterMark())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from   w  w  w. j  a va2  s  .c  o m
                public void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast("idle state",
                            new IdleStateHandler(0, 0, config.idleStateThresholdMs(), TimeUnit.MILLISECONDS));
                    ch.pipeline().addLast("heartbeat", IdleStateHeartbeatWriter.INSTANCE);
                    ch.pipeline().addLast("encoder", BaseMessageEncoder.INSTANCE);
                    ch.pipeline().addLast("decoder", new BaseMessageDecoder());
                    ch.pipeline().addLast("connector", connection);
                }
            });

    bootstrap.connect(chnlzrHost.getHostname(), chnlzrHost.getPort()).addListener(connect -> {
        if (!connect.isSuccess())
            future.setException(new ConnectException("failed to connect to chnlzr"));
    });

    return future;
}

From source file:org.testfx.util.WaitForAsyncUtils.java

/**
 * Calls the given {@link Callable} on a new {@link Thread} and returns a {@link Future} that
 * is set on finish or error./*from  w  w  w . j a v a2 s  . c  o m*/
 *
 * @param callable the callable
 * @param <T> the callable type
 * @return a future
 */
public static <T> Future<T> async(Callable<T> callable) {
    SettableFuture<T> future = SettableFuture.create();
    runOnThread(() -> callCallableAndSetFuture(callable, future));
    return future;
}

From source file:io.datakernel.service.ServiceAdapters.java

public static ServiceAdapter<EventloopService> forEventloopService() {
    return new ServiceAdapter<EventloopService>() {
        @Override//w w w .  j a v  a  2s . c o m
        public Service toService(final EventloopService instance, Executor executor) {
            return new Service() {
                @Override
                public ListenableFuture<?> start() {
                    final SettableFuture<?> future = SettableFuture.create();
                    instance.getEventloop().execute(new Runnable() {
                        @Override
                        public void run() {
                            instance.start(toCompletionCallback(future));
                        }
                    });
                    return future;
                }

                @Override
                public ListenableFuture<?> stop() {
                    final SettableFuture<?> future = SettableFuture.create();
                    instance.getEventloop().execute(new Runnable() {
                        @Override
                        public void run() {
                            instance.stop(toCompletionCallback(future));
                        }
                    });
                    return future;
                }
            };
        }
    };
}

From source file:com.mypurecloud.sdk.v2.api.BillingApiAsync.java

/**
 * Get a report of the billable usages (e.g. licenses and devices utilized) for a given period.
 * /*ww  w .  jav  a2 s  .c o m*/
 * @param request the request object
 * @param callback the action to perform when the request is completed
 * @return the future indication when the request has completed
 */
public Future<BillingUsageReport> getBillingReportsBillableusageAsync(
        GetBillingReportsBillableusageRequest request, final AsyncApiCallback<BillingUsageReport> callback) {
    try {
        final SettableFuture<BillingUsageReport> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<BillingUsageReport>() {
        }, new AsyncApiCallback<ApiResponse<BillingUsageReport>>() {
            @Override
            public void onCompleted(ApiResponse<BillingUsageReport> response) {
                notifySuccess(future, callback, response.getBody());
            }

            @Override
            public void onFailed(Throwable exception) {
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    notifySuccess(future, callback, null);
                }
            }
        });
        return future;
    } catch (Throwable exception) {
        return Futures.immediateFailedFuture(exception);
    }
}

From source file:org.retrostore.android.view.ImageLoader.java

public ListenableFuture<Bitmap> loadAsBitmapAsync(final String url, final int width, final int height) {
    final SettableFuture<Bitmap> future = SettableFuture.create();
    final Context context = mCtx.get();
    if (context == null) {
        future.setException(new RuntimeException("Context invalid."));
        return future;
    }/*w w  w  . j ava 2s. c  o  m*/

    mExecutor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                future.set(Glide.with(context).load(url).asBitmap().into(width, height).get());
            } catch (InterruptedException | ExecutionException e) {
                Log.e(TAG, "Could not load image as bitmap.", e);
                future.setException(e);
            }
        }
    });
    return future;
}

From source file:org.testfx.toolkit.impl.ApplicationServiceImpl.java

@Override
public Future<Void> init(ApplicationFixture applicationFixture) {
    // Should be called in TestFX launcher thread.
    SettableFuture<Void> future = SettableFuture.create();
    try {//  w  w  w  .ja  va  2 s .  co m
        applicationFixture.init();
        future.set(null);
    } catch (Exception exception) {
        future.setException(exception);
    }
    return future;
}

From source file:org.opendaylight.laas.impl.CentinelEventNotifierImpl.java

@Override
public Future<RpcResult<Void>> notifyEvent(NotifyEventInput input) {

    final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
    futureResult.set(RpcResultBuilder.<Void>success().build());

    notificationProvider.publish(new EventNotifiedBuilder().setEventType(input.getEventType())
            .setEventBodyType(input.getEventBodyType()).setEventBody(input.getEventBody())
            .setEventKeys(input.getEventKeys()).build());
    return futureResult;
}

From source file:com.android.camera.one.v2.initialization.CaptureSessionCreator.java

/**
 * Asynchronously creates a capture session, returning a future to it.
 *
 * @param surfaces The set of output surfaces for the camera capture
 *            session.//from ww w  .  ja v  a  2s  .  c o m
 * @return A Future for the camera capture session.
 */
public ListenableFuture<CameraCaptureSessionProxy> createCaptureSession(List<Surface> surfaces) {
    final SettableFuture<CameraCaptureSessionProxy> sessionFuture = SettableFuture.create();
    try {
        mDevice.createCaptureSession(surfaces, new CameraCaptureSessionProxy.StateCallback() {
            @Override
            public void onActive(CameraCaptureSessionProxy session) {
                // Ignore.
            }

            @Override
            public void onConfigureFailed(CameraCaptureSessionProxy session) {
                sessionFuture.cancel(true);
                session.close();
            }

            @Override
            public void onConfigured(CameraCaptureSessionProxy session) {
                boolean valueSet = sessionFuture.set(session);
                if (!valueSet) {
                    // If the future was already marked with cancellation or
                    // an exception, close the session.
                    session.close();
                }
            }

            @Override
            public void onReady(CameraCaptureSessionProxy session) {
                // Ignore.
            }

            @Override
            public void onClosed(CameraCaptureSessionProxy session) {
                sessionFuture.cancel(true);
                session.close();
            }
        }, mCameraHandler);
    } catch (CameraAccessException e) {
        sessionFuture.setException(e);
    }
    return sessionFuture;
}