Example usage for java.util.concurrent Phaser arriveAndAwaitAdvance

List of usage examples for java.util.concurrent Phaser arriveAndAwaitAdvance

Introduction

In this page you can find the example usage for java.util.concurrent Phaser arriveAndAwaitAdvance.

Prototype

public int arriveAndAwaitAdvance() 

Source Link

Document

Arrives at this phaser and awaits others.

Usage

From source file:AdderTask.java

public static void main(String[] args) {
    final int PHASE_COUNT = 2;
    Phaser phaser = new Phaser() {
        public boolean onAdvance(int phase, int parties) {
            System.out.println(//from   w  w w .  jav a2 s . c o  m
                    "Phase:" + phase + ", Parties:" + parties + ",  Arrived:" + this.getArrivedParties());
            boolean terminatePhaser = false;
            if (phase >= PHASE_COUNT - 1 || parties == 0) {
                terminatePhaser = true;
            }

            return terminatePhaser;
        }
    };
    List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
    int ADDER_COUNT = 3;
    phaser.bulkRegister(ADDER_COUNT + 1);
    for (int i = 1; i <= ADDER_COUNT; i++) {
        String taskName = "Task  #" + i;
        AdderTask task = new AdderTask(taskName, phaser, list);
        task.start();
    }
    while (!phaser.isTerminated()) {
        phaser.arriveAndAwaitAdvance();
    }
    int sum = 0;
    for (Integer num : list) {
        sum = sum + num;
    }
    System.out.println("Sum = " + sum);
}

From source file:Main.java

private static Long fib(int n) throws InterruptedException {
    AtomicLong result = new AtomicLong();
    Phaser phaser = new Phaser();
    Task initialTask = new Task(n, result, phaser);
    phaser.register();/*from   w  w w .ja va  2 s  .c  om*/
    executors.submit(initialTask);
    phaser.arriveAndAwaitAdvance();
    return result.get();
}

From source file:Entity.java

private static void gameEngine(List<Entity> entities) {
    final Phaser phaser = new Phaser(1);
    for (final Entity entity : entities) {
        final String member = entity.toString();
        System.out.println(member);
        phaser.register();/*from ww  w. j  a v a 2 s . co m*/
        new Thread() {
            @Override
            public void run() {
                System.out.println(member);
                phaser.arriveAndAwaitAdvance();
                entity.run();
            }
        }.start();
    }
    phaser.arriveAndDeregister();
}

From source file:io.getlime.push.service.PushMessageSenderService.java

/**
 * Send push notifications to given application.
 *
 * @param appId App ID used for addressing push messages. Required so that appropriate APNs/FCM credentials can be obtained.
 * @param pushMessageList List with push message objects.
 * @return Result of this batch sending.
 *///from w w w .j  av  a 2 s .co m
@Transactional
public PushMessageSendResult sendPushMessage(final Long appId, List<PushMessage> pushMessageList)
        throws PushServerException {
    // Prepare clients
    AppRelatedPushClient pushClient = prepareClients(appId);

    // Prepare synchronization primitive for parallel push message sending
    final Phaser phaser = new Phaser(1);

    // Prepare result object
    final PushMessageSendResult sendResult = new PushMessageSendResult();

    // Send push message batch
    for (PushMessage pushMessage : pushMessageList) {

        // Validate push message before sending
        validatePushMessage(pushMessage);

        // Fetch connected devices
        List<PushDeviceRegistrationEntity> devices = getPushDevices(appId, pushMessage.getUserId(),
                pushMessage.getActivationId());

        // Iterate over all devices for given user
        for (final PushDeviceRegistrationEntity device : devices) {
            final PushMessageEntity pushMessageObject = pushMessageDAO.storePushMessageObject(
                    pushMessage.getBody(), pushMessage.getAttributes(), pushMessage.getUserId(),
                    pushMessage.getActivationId(), device.getId());

            // Check if given push is not personal, or if it is, that device is in active state.
            // This avoids sending personal notifications to devices that are blocked or removed.
            boolean isMessagePersonal = pushMessage.getAttributes() != null
                    && pushMessage.getAttributes().getPersonal();
            boolean isDeviceActive = device.getActive();
            if (!isMessagePersonal || isDeviceActive) {

                // Register phaser for synchronization
                phaser.register();

                // Decide if the device is iOS or Android and send message accordingly
                String platform = device.getPlatform();
                if (platform.equals(PushDeviceRegistrationEntity.Platform.iOS)) {
                    sendMessageToIos(pushClient.getApnsClient(), pushMessage.getBody(),
                            pushMessage.getAttributes(), device.getPushToken(),
                            pushClient.getAppCredentials().getIosBundle(), new PushSendingCallback() {
                                @Override
                                public void didFinishSendingMessage(Result result,
                                        Map<String, Object> contextData) {
                                    switch (result) {
                                    case OK: {
                                        sendResult.getIos().setSent(sendResult.getIos().getSent() + 1);
                                        pushMessageObject.setStatus(PushMessageEntity.Status.SENT);
                                        pushMessageDAO.save(pushMessageObject);
                                        break;
                                    }
                                    case PENDING: {
                                        sendResult.getIos().setPending(sendResult.getIos().getPending() + 1);
                                        pushMessageObject.setStatus(PushMessageEntity.Status.PENDING);
                                        pushMessageDAO.save(pushMessageObject);
                                        break;
                                    }
                                    case FAILED: {
                                        sendResult.getIos().setFailed(sendResult.getIos().getFailed() + 1);
                                        pushMessageObject.setStatus(PushMessageEntity.Status.FAILED);
                                        pushMessageDAO.save(pushMessageObject);
                                        break;
                                    }
                                    case FAILED_DELETE: {
                                        sendResult.getIos().setFailed(sendResult.getIos().getFailed() + 1);
                                        pushMessageObject.setStatus(PushMessageEntity.Status.FAILED);
                                        pushMessageDAO.save(pushMessageObject);
                                        pushDeviceRepository.delete(device);
                                        break;
                                    }
                                    }
                                    sendResult.getIos().setTotal(sendResult.getIos().getTotal() + 1);
                                    phaser.arriveAndDeregister();
                                }
                            });
                } else if (platform.equals(PushDeviceRegistrationEntity.Platform.Android)) {
                    final String token = device.getPushToken();
                    sendMessageToAndroid(pushClient.getFcmClient(), pushMessage.getBody(),
                            pushMessage.getAttributes(), token, new PushSendingCallback() {
                                @Override
                                public void didFinishSendingMessage(Result sendingResult,
                                        Map<String, Object> contextData) {
                                    switch (sendingResult) {
                                    case OK: {
                                        sendResult.getAndroid().setSent(sendResult.getAndroid().getSent() + 1);
                                        pushMessageObject.setStatus(PushMessageEntity.Status.SENT);
                                        pushMessageDAO.save(pushMessageObject);
                                        updateFcmTokenIfNeeded(appId, token, contextData);
                                        break;
                                    }
                                    case PENDING: {
                                        sendResult.getAndroid()
                                                .setPending(sendResult.getAndroid().getPending() + 1);
                                        pushMessageObject.setStatus(PushMessageEntity.Status.PENDING);
                                        pushMessageDAO.save(pushMessageObject);
                                        break;
                                    }
                                    case FAILED: {
                                        sendResult.getAndroid()
                                                .setFailed(sendResult.getAndroid().getFailed() + 1);
                                        pushMessageObject.setStatus(PushMessageEntity.Status.FAILED);
                                        pushMessageDAO.save(pushMessageObject);
                                        break;
                                    }
                                    case FAILED_DELETE: {
                                        sendResult.getAndroid()
                                                .setFailed(sendResult.getAndroid().getFailed() + 1);
                                        pushMessageObject.setStatus(PushMessageEntity.Status.FAILED);
                                        pushMessageDAO.save(pushMessageObject);
                                        pushDeviceRepository.delete(device);
                                        break;
                                    }
                                    }
                                    sendResult.getAndroid().setTotal(sendResult.getAndroid().getTotal() + 1);
                                    phaser.arriveAndDeregister();
                                }
                            });
                }
            }
        }
    }
    phaser.arriveAndAwaitAdvance();
    return sendResult;
}