Example usage for java.util.concurrent ConcurrentLinkedQueue ConcurrentLinkedQueue

List of usage examples for java.util.concurrent ConcurrentLinkedQueue ConcurrentLinkedQueue

Introduction

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

Prototype

public ConcurrentLinkedQueue() 

Source Link

Document

Creates a ConcurrentLinkedQueue that is initially empty.

Usage

From source file:com.xylocore.cassandra.query.SharedResultSetProcessor.java

/**
 * FILLIN//from   w ww .  j av a 2 s  .  com
 * 
 * @param       aExecutionContext
 * @param       aExecutor
 * @param       aCompletionNotifier
 */
SharedResultSetProcessor(PagedQueryExecutionContext<T> aExecutionContext, Executor aExecutor,
        ResultSetCompletionNotifier<T> aCompletionNotifier) {
    Validate.notNull(aExecutionContext);
    Validate.notNull(aCompletionNotifier);

    executionContext = aExecutionContext;
    executor = aExecutor;
    completionNotifier = aCompletionNotifier;
    availableTasks = new ConcurrentLinkedQueue<>();
    availableTaskCount = new AtomicInteger(aExecutionContext.getConcurrencyLevel());
    state = new AtomicReference<>(State.Inactive);
    workTasksLocked = new AtomicBoolean(false);
    fetchFuture = null;
    completed = false;
    resultSet = null;
    currentWorkTask = null;

    for (int i = 0, ci = aExecutionContext.getConcurrencyLevel(); i < ci; i++) {
        WorkTask myWorkTask = new WorkTask(i);

        availableTasks.offer(myWorkTask);
    }
}

From source file:asia.stampy.server.listener.subscription.AbstractAcknowledgementListenerAndInterceptor.java

@Override
public void interceptMessage(StampyMessage<?> message, HostPort hostPort) throws InterceptException {
    MessageMessage msg = (MessageMessage) message;

    String ack = msg.getHeader().getAck();

    Queue<String> queue = messages.get(hostPort);
    if (queue == null) {
        queue = new ConcurrentLinkedQueue<String>();
        messages.put(hostPort, queue);/*from   w w  w  . j a  v a2  s .c o  m*/
    }

    queue.add(ack);
    startTimerTask(hostPort, ack);
}

From source file:org.apache.hadoop.mapreduce.v2.app.rm.RMCommunicator.java

public RMCommunicator(ClientService clientService, AppContext context) {
    super("RMCommunicator");
    this.clientService = clientService;
    this.context = context;
    this.eventHandler = context.getEventHandler();
    this.applicationId = context.getApplicationID();
    this.stopped = new AtomicBoolean(false);
    this.heartbeatCallbacks = new ConcurrentLinkedQueue<Runnable>();
    this.schedulerResourceTypes = EnumSet.of(SchedulerResourceTypes.MEMORY);
}

From source file:com.comcast.viper.flume2storm.connection.receptor.KryoNetEventReceptor.java

/**
 * @param connectionParams//from   w w w  . j  a v  a 2s .  com
 *          Connection parameters to the {@link KryoNetEventSender}
 * @param kryoNetParams
 *          Generic parameters of the {@link KryoNetEventReceptor}
 */
public KryoNetEventReceptor(final KryoNetConnectionParameters connectionParams,
        KryoNetParameters kryoNetParams) {
    Preconditions.checkNotNull(connectionParams);
    this.kryoNetParameters = kryoNetParams;
    this.connectionParams = connectionParams;
    stats = new EventReceptorStats(connectionParams.getId());
    listeners = new AtomicReference<>(ImmutableList.copyOf(new ArrayList<EventReceptorListener>()));
    events = new ConcurrentLinkedQueue<F2SEvent>();
    keepRunning = new AtomicBoolean(false);
    nextConnectionTime = new AtomicReference<Instant>(new Instant(0));
}

From source file:voldemort.server.niosocket.NioSelectorManager.java

public NioSelectorManager(InetSocketAddress endpoint, RequestHandlerFactory requestHandlerFactory,
        int socketBufferSize) {
    this.endpoint = endpoint;
    this.socketChannelQueue = new ConcurrentLinkedQueue<SocketChannel>();
    this.requestHandlerFactory = requestHandlerFactory;
    this.socketBufferSize = socketBufferSize;
    this.numActiveConnections = new MutableInt(0);
}

From source file:org.rifidi.edge.core.sensors.sessions.AbstractSensorSession.java

/**
 * Constructor/* w ww.  ja  v  a2  s  . c o m*/
 * 
 * @param sensor
 * @param ID
 *            ID of this SensorSession
 * @param destination
 *            The JMS Queue to add Tag Data to
 * @param template
 *            The Template used to send Tag data to the internal queue
 * @param commandConfigurations
 *            Provided by spring
 */
public AbstractSensorSession(AbstractSensor<?> sensor, String ID,
        Set<AbstractCommandConfiguration<?>> commandConfigurations) {
    super(ID, sensor);
    this.commandConfigurations = commandConfigurations;
    status = SessionStatus.CREATED;
    this.queuedCommands = new ConcurrentLinkedQueue<CommandExecutor>();
    this.runningCommands = Collections.synchronizedList(new LinkedList<CommandExecutor>());
}

From source file:com.norconex.committer.core.AbstractFileQueueCommitter.java

@Override
public void commit() {

    // Get all files to be committed, relying on natural ordering which 
    // will be in file creation order.
    final Queue<File> filesPending = new ConcurrentLinkedQueue<File>();
    FileUtil.visitAllFiles(new File(queue.getDirectory()), new IFileVisitor() {
        @Override//from  w w w  . j a  v a  2 s  .co  m
        public void visit(File file) {
            filesPending.add(file);
        }
    }, REF_FILTER);

    // Nothing left to commit. This happens if multiple threads are 
    // committing at the same time and no more files are available for the 
    // current thread to commit. This should happen rarely in practice.
    if (filesPending.isEmpty()) {
        return;
    }

    // Don't commit more than queue size
    List<ICommitOperation> filesToCommit = new ArrayList<>();
    while (filesToCommit.size() < queueSize) {

        File file = filesPending.poll();

        // If no more files available in both list, quit loop. This happens 
        // if multiple threads tries to commit at once and there is less 
        // than queueSize files to commit. This should happen rarely in
        // practice.
        if (file == null) {
            break;
        }

        // Current thread tries to own this file. If the file is already own
        // by another thread, continue and attempt to grab another file.
        if (filesCommitting.putIfAbsent(file, Thread.currentThread()) != null) {
            continue;
        }

        // A file might have already been committed and cleanup from 
        // the map, but still returned by the directory listing. Ignore 
        // those. It is important to make this check AFTER the current  
        // thread got ownership of the file. 
        if (!file.exists()) {
            continue;
        }

        // Current thread will be committing this file
        if (file.getAbsolutePath().contains(FileSystemCommitter.FILE_SUFFIX_ADD)) {
            filesToCommit.add(new FileAddOperation(file));
        } else if (file.getAbsolutePath().contains(FileSystemCommitter.FILE_SUFFIX_REMOVE)) {
            filesToCommit.add(new FileDeleteOperation(file));
        } else {
            LOG.error("Unsupported file to commit: " + file);
        }
    }

    if (LOG.isInfoEnabled()) {
        LOG.info(String.format("Committing %s files", filesToCommit.size()));
    }
    for (ICommitOperation op : filesToCommit) {
        try {
            if (op instanceof FileAddOperation) {
                prepareCommitAddition((IAddOperation) op);
                commitAddition((IAddOperation) op);
            } else {
                prepareCommitDeletion((IDeleteOperation) op);
                commitDeletion((IDeleteOperation) op);
            }
        } catch (IOException e) {
            throw new CommitterException("Cannot read reference from : " + op, e);
        }
    }

    commitComplete();

    deleteEmptyOldDirs(new File(queue.getDirectory()));

    // Cleanup committed files from map that might have been deleted
    Enumeration<File> en = filesCommitting.keys();
    while (en.hasMoreElements()) {
        File file = (File) en.nextElement();
        if (!file.exists()) {
            filesCommitting.remove(file);
        }
    }
}

From source file:com.netflix.discovery.shared.Applications.java

/**
 * Create a new Eureka application list, based on the provided applications.  The provided container is
 * not modified./*from   w  w w  .  j  a v  a  2  s .c o  m*/
 *
 * @param apps the initial list of apps to store in this applications list
 */
public Applications(List<Application> apps) {
    this.applications = new ConcurrentLinkedQueue<Application>();
    this.applications.addAll(apps);
}

From source file:org.siddhiesb.transport.passthru.DeliveryAgent.java

/**
 * This method queues the message for delivery. If a connection is already existing for
 * the destination epr, the message will be delivered immediately. Otherwise message has
 * to wait until a connection is established. In this case this method will inform the
 * system about the need for a connection.
 *
 * @param commonContext the message context to be sent
 *//*from  w ww  . jav a 2  s.com*/
public void submit(CommonContext commonContext) {
    try {

        String toAddress = (String) commonContext.getProperty(CommonAPIConstants.ENDPOINT);
        URL url = new URL(toAddress);
        String scheme = url.getProtocol() != null ? url.getProtocol() : "http";
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            // use default
            if ("http".equals(scheme)) {
                port = 80;
            } else if ("https".equals(scheme)) {
                port = 443;
            }
        }
        HttpHost target = new HttpHost(hostname, port, scheme);
        boolean secure = "https".equalsIgnoreCase(target.getSchemeName());

        HttpHost proxy = null; //proxyConfig.selectProxy(target);

        HttpRoute route;
        if (proxy != null) {
            route = new HttpRoute(target, null, proxy, secure);
        } else {
            route = new HttpRoute(target, null, secure);
        }

        // first we queue the message
        Queue<CommonContext> queue = null;
        lock.lock();
        try {
            queue = waitingMessages.get(route);
            if (queue == null) {
                queue = new ConcurrentLinkedQueue<CommonContext>();
                waitingMessages.put(route, queue);
            }
            if (queue.size() == maxWaitingMessages) {
                CommonContext msgCtx = queue.poll();
            }

            queue.add(commonContext);
        } finally {
            lock.unlock();
        }

        NHttpClientConnection conn = targetConnections.getConnection(route);
        if (conn != null) {
            conn.resetInput();
            conn.resetOutput();
            CommonContext commonContext1 = queue.poll();

            if (commonContext1 != null) {
                tryNextMessage(commonContext1, route, conn);
            }
        }

    } catch (MalformedURLException e) {
        handleException("Malformed URL in the target EPR", e);
    }
}

From source file:org.wso2.carbon.registry.eventing.RegistryEventDispatcher.java

public RegistryEventDispatcher() {
    digestQueues = new LinkedHashMap<String, Queue<DigestEntry>>();
    for (String s : new String[] { "h", "d", "w", "f", "m", "y" }) {
        //TODO: Identify Queuing mechanisms.
        digestQueues.put(s, new ConcurrentLinkedQueue<DigestEntry>());
    }/*from w w  w .j av a2s .  c o  m*/
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            GregorianCalendar utc = new GregorianCalendar(SimpleTimeZone.getTimeZone("UTC"));
            Map<String, List<DigestEntry>> digestEntries = new HashMap<String, List<DigestEntry>>();
            try {
                addToDigestEntryQueue(digestEntries, "h");
                if (utc.get(Calendar.HOUR_OF_DAY) == 0) {
                    addToDigestEntryQueue(digestEntries, "d");
                    if (utc.get(Calendar.DAY_OF_WEEK) == 1) {
                        addToDigestEntryQueue(digestEntries, "w");
                        if (utc.get(Calendar.WEEK_OF_YEAR) % 2 != 0) {
                            addToDigestEntryQueue(digestEntries, "f");
                        }
                    }
                    if (utc.get(Calendar.DAY_OF_MONTH) == 1) {
                        addToDigestEntryQueue(digestEntries, "m");
                        if (utc.get(Calendar.DAY_OF_YEAR) == 1) {
                            addToDigestEntryQueue(digestEntries, "y");

                        }
                    }
                }
                for (Map.Entry<String, List<DigestEntry>> e : digestEntries.entrySet()) {
                    List<DigestEntry> value = e.getValue();
                    Collections.sort(value, new Comparator<DigestEntry>() {
                        public int compare(DigestEntry o1, DigestEntry o2) {
                            if (o1.getTime() > o2.getTime()) {
                                return -1;
                            } else if (o1.getTime() < o2.getTime()) {
                                return 1;
                            }
                            return 0;
                        }
                    });
                    StringBuffer buffer = new StringBuffer();
                    for (DigestEntry entry : value) {
                        buffer.append(entry.getMessage()).append("\n\n");
                    }
                    RegistryEvent<String> re = new RegistryEvent<String>(buffer.toString());
                    re.setTopic(RegistryEvent.TOPIC_SEPARATOR + "DigestEvent");
                    DispatchEvent de = new DispatchEvent(re, e.getKey(), true);
                    Subscription subscription = new Subscription();
                    subscription.setTopicName(re.getTopic());
                    publishEvent(de, subscription, e.getKey(), true);
                }
            } catch (RuntimeException ignored) {
                // Eat any runtime exceptions that occurred, we don't care if the message went
                // or not.
            }
        }
    }, System.currentTimeMillis() % (1000 * 60 * 60), 1000 * 60 * 60, TimeUnit.MILLISECONDS);
    try {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                executorService.shutdownNow();
            }
        });
    } catch (IllegalStateException e) {
        executorService.shutdownNow();
        throw new IllegalStateException(
                "Unable to create registry event dispatcher during " + "shutdown process.");
    }
}