Example usage for java.util.concurrent ArrayBlockingQueue offer

List of usage examples for java.util.concurrent ArrayBlockingQueue offer

Introduction

In this page you can find the example usage for java.util.concurrent ArrayBlockingQueue offer.

Prototype

public boolean offer(E e) 

Source Link

Document

Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and false if this queue is full.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int capacity = 10;
    ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

    for (int i = 0; i < 10; i++) {
        queue.add(i);/*  ww  w. j  a  va2  s.c o  m*/
    }
    queue.offer(9999);
    System.out.println(queue);
}

From source file:io.teak.sdk.TeakNotification.java

/**
 * Cancel a push notification that was scheduled with {@link TeakNotification#scheduleNotification(String, String, long)}
 *
 * @param scheduleId/*  ww w .  j  a  va 2 s .c o m*/
 * @return
 */
@SuppressWarnings("unused")
public static FutureTask<String> cancelNotification(final String scheduleId) {
    if (!Teak.isEnabled()) {
        Log.e(LOG_TAG, "Teak is disabled, ignoring cancelNotification().");
        return null;
    }

    if (scheduleId == null || scheduleId.isEmpty()) {
        Log.e(LOG_TAG, "scheduleId cannot be null or empty");
        return null;
    }

    final ArrayBlockingQueue<String> q = new ArrayBlockingQueue<>(1);
    final FutureTask<String> ret = new FutureTask<>(new Callable<String>() {
        public String call() {
            try {
                return q.take();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            }
            return null;
        }
    });

    Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
        @Override
        public void run(Session session) {
            HashMap<String, Object> payload = new HashMap<>();
            payload.put("id", scheduleId);

            new Request("/me/cancel_local_notify.json", payload, session) {
                @Override
                protected void done(int responseCode, String responseBody) {
                    try {
                        JSONObject response = new JSONObject(responseBody);
                        if (response.getString("status").equals("ok")) {
                            q.offer(response.getJSONObject("event").getString("id"));
                        } else {
                            q.offer("");
                        }
                    } catch (Exception ignored) {
                        q.offer("");
                    }
                    ret.run();
                }
            }.run();
        }
    });

    return ret;
}

From source file:io.teak.sdk.TeakNotification.java

/**
 * Schedules a push notification for some time in the future.
 *
 * @param creativeId     The identifier of the notification in the Teak dashboard (will create if not found).
 * @param defaultMessage The default message to send, may be over-ridden in the dashboard.
 * @param delayInSeconds The delay in seconds from now to send the notification.
 * @return The identifier of the scheduled notification (see {@link TeakNotification#cancelNotification(String)} or null.
 *///from   w w  w.j  a va 2  s  .c o m
@SuppressWarnings("unused")
public static FutureTask<String> scheduleNotification(final String creativeId, final String defaultMessage,
        final long delayInSeconds) {
    if (!Teak.isEnabled()) {
        Log.e(LOG_TAG, "Teak is disabled, ignoring scheduleNotification().");
        return null;
    }

    if (creativeId == null || creativeId.isEmpty()) {
        Log.e(LOG_TAG, "creativeId cannot be null or empty");
        return null;
    }

    if (defaultMessage == null || defaultMessage.isEmpty()) {
        Log.e(LOG_TAG, "defaultMessage cannot be null or empty");
        return null;
    }

    final ArrayBlockingQueue<String> q = new ArrayBlockingQueue<>(1);
    final FutureTask<String> ret = new FutureTask<>(new Callable<String>() {
        public String call() {
            try {
                return q.take();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            }
            return null;
        }
    });

    Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
        @Override
        public void run(Session session) {
            HashMap<String, Object> payload = new HashMap<>();
            payload.put("identifier", creativeId);
            payload.put("message", defaultMessage);
            payload.put("offset", delayInSeconds);

            new Request("/me/local_notify.json", payload, session) {
                @Override
                protected void done(int responseCode, String responseBody) {
                    try {
                        JSONObject response = new JSONObject(responseBody);
                        if (response.getString("status").equals("ok")) {
                            q.offer(response.getJSONObject("event").getString("id"));
                        } else {
                            q.offer("");
                        }
                    } catch (Exception ignored) {
                        q.offer("");
                    }

                    ret.run();
                }
            }.run();
        }
    });
    return ret;
}

From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java

@Test
@Ignore/*from   w  ww . j av a 2 s.c o  m*/
public void testReplicationQuorumLoss() throws Throwable {

    System.out.println("======================================");
    System.out.println(" Start 2 ActiveMQ nodes.");
    System.out.println("======================================");
    startBrokerAsync(createBrokerNode("node-1", port));
    startBrokerAsync(createBrokerNode("node-2", port));
    BrokerService master = waitForNextMaster();
    System.out.println("======================================");
    System.out.println(" Start the producer and consumer");
    System.out.println("======================================");

    final AtomicBoolean stopClients = new AtomicBoolean(false);
    final ArrayBlockingQueue<String> errors = new ArrayBlockingQueue<String>(100);
    final AtomicLong receivedCounter = new AtomicLong();
    final AtomicLong sentCounter = new AtomicLong();
    Thread producer = startFailoverClient("producer", new Client() {
        @Override
        public void execute(Connection connection) throws Exception {
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(session.createQueue("test"));
            long actual = 0;
            while (!stopClients.get()) {
                TextMessage msg = session.createTextMessage("Hello World");
                msg.setLongProperty("id", actual++);
                producer.send(msg);
                sentCounter.incrementAndGet();
            }
        }
    });

    Thread consumer = startFailoverClient("consumer", new Client() {
        @Override
        public void execute(Connection connection) throws Exception {
            connection.start();
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            MessageConsumer consumer = session.createConsumer(session.createQueue("test"));
            long expected = 0;
            while (!stopClients.get()) {
                Message msg = consumer.receive(200);
                if (msg != null) {
                    long actual = msg.getLongProperty("id");
                    if (actual != expected) {
                        errors.offer("Received got unexpected msg id: " + actual + ", expected: " + expected);
                    }
                    msg.acknowledge();
                    expected = actual + 1;
                    receivedCounter.incrementAndGet();
                }
            }
        }
    });

    try {
        assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS);
        assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS);
        assertNull(errors.poll());

        System.out.println("======================================");
        System.out.println(" Master should stop once the quorum is lost.");
        System.out.println("======================================");
        ArrayList<BrokerService> stopped = stopSlaves();// stopping the slaves should kill the quorum.
        assertStopsWithin(master, 10, TimeUnit.SECONDS);
        assertNull(errors.poll()); // clients should not see an error since they are failover clients.
        stopped.add(master);

        System.out.println("======================================");
        System.out.println(" Restart the slave. Clients should make progress again..");
        System.out.println("======================================");
        startBrokersAsync(createBrokerNodes(stopped));
        assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS);
        assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS);
        assertNull(errors.poll());
    } catch (Throwable e) {
        e.printStackTrace();
        throw e;
    } finally {
        // Wait for the clients to stop..
        stopClients.set(true);
        producer.join();
        consumer.join();
    }
}