Example usage for java.util.concurrent ConcurrentLinkedQueue isEmpty

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

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this queue contains no elements.

Usage

From source file:com.ibm.crail.storage.StorageServer.java

public static void main(String[] args) throws Exception {
    Logger LOG = CrailUtils.getLogger();
    CrailConfiguration conf = new CrailConfiguration();
    CrailConstants.updateConstants(conf);
    CrailConstants.printConf();/*from ww w.j  a  v  a  2s . com*/
    CrailConstants.verify();

    int splitIndex = 0;
    for (String param : args) {
        if (param.equalsIgnoreCase("--")) {
            break;
        }
        splitIndex++;
    }

    //default values
    StringTokenizer tokenizer = new StringTokenizer(CrailConstants.STORAGE_TYPES, ",");
    if (!tokenizer.hasMoreTokens()) {
        throw new Exception("No storage types defined!");
    }
    String storageName = tokenizer.nextToken();
    int storageType = 0;
    HashMap<String, Integer> storageTypes = new HashMap<String, Integer>();
    storageTypes.put(storageName, storageType);
    for (int type = 1; tokenizer.hasMoreElements(); type++) {
        String name = tokenizer.nextToken();
        storageTypes.put(name, type);
    }
    int storageClass = -1;

    //custom values
    if (args != null) {
        Option typeOption = Option.builder("t").desc("storage type to start").hasArg().build();
        Option classOption = Option.builder("c").desc("storage class the server will attach to").hasArg()
                .build();
        Options options = new Options();
        options.addOption(typeOption);
        options.addOption(classOption);
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, splitIndex));
            if (line.hasOption(typeOption.getOpt())) {
                storageName = line.getOptionValue(typeOption.getOpt());
                storageType = storageTypes.get(storageName).intValue();
            }
            if (line.hasOption(classOption.getOpt())) {
                storageClass = Integer.parseInt(line.getOptionValue(classOption.getOpt()));
            }
        } catch (ParseException e) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Storage tier", options);
            System.exit(-1);
        }
    }
    if (storageClass < 0) {
        storageClass = storageType;
    }

    StorageTier storageTier = StorageTier.createInstance(storageName);
    if (storageTier == null) {
        throw new Exception("Cannot instantiate datanode of type " + storageName);
    }

    String extraParams[] = null;
    splitIndex++;
    if (args.length > splitIndex) {
        extraParams = new String[args.length - splitIndex];
        for (int i = splitIndex; i < args.length; i++) {
            extraParams[i - splitIndex] = args[i];
        }
    }
    storageTier.init(conf, extraParams);
    storageTier.printConf(LOG);

    RpcClient rpcClient = RpcClient.createInstance(CrailConstants.NAMENODE_RPC_TYPE);
    rpcClient.init(conf, args);
    rpcClient.printConf(LOG);

    ConcurrentLinkedQueue<InetSocketAddress> namenodeList = CrailUtils.getNameNodeList();
    ConcurrentLinkedQueue<RpcConnection> connectionList = new ConcurrentLinkedQueue<RpcConnection>();
    while (!namenodeList.isEmpty()) {
        InetSocketAddress address = namenodeList.poll();
        RpcConnection connection = rpcClient.connect(address);
        connectionList.add(connection);
    }
    RpcConnection rpcConnection = connectionList.peek();
    if (connectionList.size() > 1) {
        rpcConnection = new RpcDispatcher(connectionList);
    }
    LOG.info("connected to namenode(s) " + rpcConnection.toString());

    StorageServer server = storageTier.launchServer();
    StorageRpcClient storageRpc = new StorageRpcClient(storageType, CrailStorageClass.get(storageClass),
            server.getAddress(), rpcConnection);

    HashMap<Long, Long> blockCount = new HashMap<Long, Long>();
    long sumCount = 0;
    while (server.isAlive()) {
        StorageResource resource = server.allocateResource();
        if (resource == null) {
            break;
        } else {
            storageRpc.setBlock(resource.getAddress(), resource.getLength(), resource.getKey());
            DataNodeStatistics stats = storageRpc.getDataNode();
            long newCount = stats.getFreeBlockCount();
            long serviceId = stats.getServiceId();

            long oldCount = 0;
            if (blockCount.containsKey(serviceId)) {
                oldCount = blockCount.get(serviceId);
            }
            long diffCount = newCount - oldCount;
            blockCount.put(serviceId, newCount);
            sumCount += diffCount;
            LOG.info("datanode statistics, freeBlocks " + sumCount);
        }
    }

    while (server.isAlive()) {
        DataNodeStatistics stats = storageRpc.getDataNode();
        long newCount = stats.getFreeBlockCount();
        long serviceId = stats.getServiceId();

        long oldCount = 0;
        if (blockCount.containsKey(serviceId)) {
            oldCount = blockCount.get(serviceId);
        }
        long diffCount = newCount - oldCount;
        blockCount.put(serviceId, newCount);
        sumCount += diffCount;

        LOG.info("datanode statistics, freeBlocks " + sumCount);
        Thread.sleep(2000);
    }
}

From source file:Main.java

private static byte[] mergeBytes(byte[] in, ConcurrentLinkedQueue<byte[]> decompressUnfinishedDataQueue) {

    if (!decompressUnfinishedDataQueue.isEmpty()) {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {// ww w  . j  a v  a2  s  .  c  om
            while (!decompressUnfinishedDataQueue.isEmpty()) {
                out.write(decompressUnfinishedDataQueue.poll());
            }
            out.write(in);
            in = out.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
    return in;
}

From source file:net.jmhertlein.mcanalytics.plugin.daemon.ClientMonitor.java

private void write(PrintWriter out) {
    ConcurrentLinkedQueue<JSONObject> queue = dispatcher.getWriteQueue();
    while (!shutdown) {
        if (queue.isEmpty()) {
            synchronized (queue) {
                try {
                    queue.wait();/*from   www . ja v  a  2 s.  c om*/
                    System.out.println("CL-WRITE: Got something to write!");
                } catch (InterruptedException ex) {
                }
            }
        } else {
            String w = queue.remove().toString();
            //System.out.println("CL-WRITE: WRITING THIS:=======================");
            //System.out.println(w);
            //System.out.println("==============================================");
            out.println(w);
            out.flush();
        }
    }

    //System.out.println("CL-WRITE: Exiting, turning off the lights...");
    try {
        close();
    } catch (IOException ex) {
        Logger.getLogger(ClientMonitor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:io.pravega.controller.eventProcessor.impl.SerializedRequestHandler.java

private void handleWorkComplete(String key, ConcurrentLinkedQueue<Work> workQueue, Work work) {
    work.getResult().whenComplete((rw, ew) -> {
        boolean toExecute = false;
        synchronized (lock) {
            if (workQueue.isEmpty()) {
                workers.remove(key);/*  w  w w .j  a  v  a  2  s . c om*/
            } else {
                toExecute = true;
            }
        }

        if (toExecute) {
            executor.execute(() -> run(key, workQueue));
        }
    });
}

From source file:com.mobilehelix.appserver.push.PushManager.java

public void refresh(Session sess, Long appID) {
    String combinedUser = MessageFormat.format("{0}|{1}",
            new Object[] { sess.getClient(), sess.getCredentials().getUsername() });
    ConcurrentLinkedQueue<PushReceiver> receivers = this.userPushMap.get(combinedUser);
    if (receivers != null && !receivers.isEmpty()) {
        for (PushReceiver receiver : receivers) {
            if (receiver.matches(sess.getClient(), sess.getCredentials().getUsername(), appID)) {
                receiver.refresh();//from   www.  j  a  va  2  s .c  o m
            }
        }
    }
}

From source file:com.mobilehelix.appserver.push.PushManager.java

public PushReceiver getReceiver(String client, String userID, Long appID) {
    String combinedUser = this.getCombinedUser(client, userID);
    ConcurrentLinkedQueue<PushReceiver> receivers = this.userPushMap.get(combinedUser);
    if (receivers != null && !receivers.isEmpty()) {
        for (PushReceiver receiver : receivers) {
            if (receiver.matches(client, userID, appID)) {
                return receiver;
            }// ww w . j a va 2 s .c o m
        }
    }
    return null;
}

From source file:com.mobilehelix.appserver.push.PushManager.java

public void addSession(String client, String userID, String password, String deviceType, Long appID,
        Integer appGenID) throws AppserverSystemException {
    ApplicationSettings as = appRegistry.getSettingsForAppID(client, appID, appGenID);
    if (as == null) {
        /* The registration does not tell us the app type. Hence we may get
         * normal web apps in our ID list. We just need to skip these ...
         *//*from w  w  w. j  a v  a  2 s  .c o m*/
        return;
    }
    if (as.getPushReceiver() == null) {
        /**
         * App does not support push.
         */
        return;
    }
    LOG.log(Level.FINE, "Create or refresh push session for app {0}", as.getAppName());

    // See if we have a push receiver for client/user/app
    boolean found = false;
    String combinedUser = this.getCombinedUser(client, userID);
    ConcurrentLinkedQueue<PushReceiver> receivers = this.userPushMap.get(combinedUser);
    if (receivers != null && !receivers.isEmpty()) {
        for (PushReceiver receiver : receivers) {
            if (receiver.matches(client, userID, appID)) {
                found = true;
                LOG.log(Level.INFO, "Refreshing push session for {0}", combinedUser);
                receiver.refresh(userID, password, as, true);
            }
        }
    }
    try {
        if (!found) {
            LOG.log(Level.INFO, "Creating push session for {0}", combinedUser);
            String uniqueID = this.getUniqueID(client, userID, appID);
            PushReceiver newReceiver = as.getPushReceiver();
            PushCompletion pushAccepted = new PushCompletion(this.userPushMap, this.idMap, uniqueID,
                    combinedUser, newReceiver);
            pushInit.doInit(newReceiver, asHostPlusPort, uniqueID, combinedUser, client, userID, password,
                    deviceType, appID, as, pushAccepted);
            /*
                    
            if (newReceiver.create(asHostPlusPort, uniqueID, newSess.getClient(), newSess.getUserID(), newSess.getPassword(), newSess.getDeviceType(), as)) {
            LOG.log(Level.FINE, "Created push session for {0}, ID {1}", new Object[] {
                combinedUser,
                uniqueID
            });   
            } */
        }
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
        LOG.log(Level.SEVERE, "Failed to create push session.", ex);
        throw new AppserverSystemException("Failed to create push session.", "FailedToCreatePushSession",
                new String[] { ex.getMessage() });
    }
}

From source file:org.geowebcache.storage.JobObject.java

private void addLogs(ConcurrentLinkedQueue<JobLogObject> logs) {
    JobLogObject joblog;//from   w  ww .ja  v a 2 s  .  c o m
    while (!logs.isEmpty()) {
        synchronized (logs) {
            joblog = logs.poll();
        }
        synchronized (newLogs) {
            newLogs.add(joblog);
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.RDFServiceJena.java

private List<Statement> sort(List<Statement> stmts) {
    List<Statement> output = new ArrayList<Statement>();
    int originalSize = stmts.size();
    if (originalSize == 1) {
        return stmts;
    }/*from  w ww.jav a 2 s  . c  o m*/
    List<Statement> remaining = stmts;
    ConcurrentLinkedQueue<Resource> subjQueue = new ConcurrentLinkedQueue<Resource>();
    for (Statement stmt : remaining) {
        if (stmt.getSubject().isURIResource()) {
            subjQueue.add(stmt.getSubject());
            break;
        }
    }
    if (subjQueue.isEmpty()) {
        log.warn("No named subject in statement patterns");
        return stmts;
    }
    while (remaining.size() > 0) {
        if (subjQueue.isEmpty()) {
            subjQueue.add(remaining.get(0).getSubject());
        }
        while (!subjQueue.isEmpty()) {
            Resource subj = subjQueue.poll();
            List<Statement> temp = new ArrayList<Statement>();
            for (Statement stmt : remaining) {
                if (stmt.getSubject().equals(subj)) {
                    output.add(stmt);
                    if (stmt.getObject().isResource()) {
                        subjQueue.add((Resource) stmt.getObject());
                    }
                } else {
                    temp.add(stmt);
                }
            }
            remaining = temp;
        }
    }
    if (output.size() != originalSize) {
        throw new RuntimeException(
                "original list size was " + originalSize + " but sorted size is " + output.size());
    }
    return output;
}

From source file:org.geowebcache.storage.jdbc.jobstore.JDBCJobWrapper.java

/**
 * Goes through recently added logs for this job and persists them
 * Clears recent logs from the list of recent logs. 
 * Uses a ConcurrentLinkedQueue and is threadsafe. 
 * @param stObj/*  w  w  w  .  jav a  2  s.co  m*/
 * @param conn
 * @throws SQLException 
 * @throws StorageException 
 */
private void putRecentJobLogs(JobObject stObj, Connection conn) throws StorageException, SQLException {
    ConcurrentLinkedQueue<JobLogObject> logs = stObj.getNewLogs();

    while (!logs.isEmpty()) {
        JobLogObject joblog;
        synchronized (logs) {
            joblog = logs.poll();
        }
        // Make sure the joblog points to this job. Sometimes a job might have logs before first 
        // being saved so the logs won't be pointing to the right ID yet.
        joblog.setJobId(stObj.getJobId());
        putJobLog(joblog);
    }
}