Example usage for java.util.concurrent PriorityBlockingQueue PriorityBlockingQueue

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

Introduction

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

Prototype

public PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator) 

Source Link

Document

Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.

Usage

From source file:pt.webdetails.cda.cache.scheduler.CacheScheduleManager.java

private void initQueue() throws PluginHibernateException {
    Session s = getHibernateSession();/*  w ww  .  j  a  v a  2s . c o  m*/
    s.beginTransaction();

    @SuppressWarnings("unchecked")
    List<CachedQuery> cachedQueries = s.createQuery("from " + CachedQuery.class.getSimpleName()).list();
    this.queue = new PriorityBlockingQueue<CachedQuery>(20, new SortByTimeDue());
    for (CachedQuery cq : cachedQueries) {
        if (cq.getLastExecuted() == null) {
            cq.setLastExecuted(new Date(0L));
        }
        Date nextExecution;
        try {
            nextExecution = new CronExpression(cq.getCronString()).getNextValidTimeAfter(new Date());
        } catch (ParseException ex) {
            nextExecution = new Date(0);
            logger.error("Failed to schedule " + cq.toString());
        }
        cq.setNextExecution(nextExecution);
        this.queue.add(cq);

        s.save(cq);
    }

    s.flush();
    s.getTransaction().commit();
    s.close();
}

From source file:com.streamsets.pipeline.lib.dirspooler.DirectorySpooler.java

public void init(String sourceFile) {
    try {//from   ww w . j a  va2 s  .  c o m
        spoolDirPath = fs.getFile(spoolDir);

        if (StringUtils.isEmpty(sourceFile)) {
            this.currentFile = null;
        } else {
            // sourceFile can contain: a filename, a partial path (relative to spoolDirPath),
            // or a full path.
            this.currentFile = fs.getFile(spoolDir, sourceFile);
            if (this.currentFile.getParent() == null
                    || !(this.currentFile.getParent().toString().contains(spoolDirPath.toString()))) {
                // if filename only or not full path - add the full path to the filename
                this.currentFile = fs.getFile(spoolDirPath.toString(), sourceFile);
            }
        }

        if (!waitForPathAppearance) {
            checkBaseDir(spoolDirPath);
        }
        if (postProcessing == FilePostProcessing.ARCHIVE) {
            archiveDirPath = fs.getFile(archiveDir);
            checkBaseDir(archiveDirPath);
        }
        if (errorArchiveDir != null) {
            errorArchiveDirPath = fs.getFile(errorArchiveDir);
            checkBaseDir(errorArchiveDirPath);
        }

        LOG.debug("Spool directory '{}', file pattern '{}', current file '{}'", spoolDirPath, pattern,
                currentFile);
        String extraInfo = "";
        if (postProcessing == FilePostProcessing.ARCHIVE) {
            extraInfo = Utils.format(", archive directory '{}', retention '{}' minutes", archiveDirPath,
                    archiveRetentionMillis / 60 / 1000);
        }
        LOG.debug("Post processing mode '{}'{}", postProcessing, extraInfo);

        // 11 is the DEFAULT_INITIAL_CAPACITY -- seems pretty random, but lets use the same one.
        filesQueue = new PriorityBlockingQueue<>(11, pathComparator);
        filesSet = new HashSet<>(); //Set to speed up "contains" search for filesQueue

        spoolQueueMeter = context.createMeter("spoolQueue");

        pendingFilesCounter = context.createCounter(PENDING_FILES);

        if (!waitForPathAppearance) {
            startSpooling(currentFile);
        }

    } catch (IOException ex) {
        destroy();
        throw new RuntimeException(ex);
    }
}

From source file:se.kth.ssvl.tslab.bytewalla.androiddtn.servlib.bundling.BundleDaemon.java

/**
 * Object initialization function/*from w  ww .  j av  a 2s.  c  om*/
 */
public void do_init() {

    BundleProtocol.init_default_processors();
    shutting_down_ = false;
    actions_ = new BundleActions();
    contactmgr_ = ContactManager.getInstance();
    custody_bundles_ = new BundleList("custody_bundles");
    event_ticket_ = new Integer(0);
    eventq_ = new PriorityBlockingQueue<BundleEvent>(event_queue_capacity_,
            BundleEventPriorityComparator.getInstance());
    fragmentmgr_ = FragmentManager.getInstance();
    pending_bundles_ = new BundleList("pending_bundles");
    reg_table_ = RegistrationTable.getInstance();
    stats_ = new Stats();
    params_ = new Params();
}

From source file:org.jiemamy.utils.collection.CollectionsUtil.java

/**
 * {@link PriorityBlockingQueue}?????/*from   w  ww.  j  a  va  2s.c o m*/
 * 
 * @param <E> {@link PriorityBlockingQueue}??
 * @param initialCapacity ?????
 * @param comparator ???????
 * @return {@link PriorityBlockingQueue}???
 * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less than 1
 * @see PriorityBlockingQueue#PriorityBlockingQueue(int, Comparator)
 */
public static <E> PriorityBlockingQueue<E> newPriorityBlockingQueue(int initialCapacity,
        Comparator<? super E> comparator) {
    return new PriorityBlockingQueue<E>(initialCapacity, comparator);
}

From source file:com.mobiperf.MeasurementScheduler.java

/**
 * Update the schedule based on a set of tasks from the server.
 * <p>/*from  w ww. j a  v  a  2  s. c  o  m*/
 * The current tasks to schedule are in a hash table indexed by a unique task key.
 * <p>
 * Remove all tasks from the schedule that are not in the new list or that have changed.
 * Then, add all tasks from the new list that were not in the schedule, or have changed.
 * Then, the schedule will match the one in the server, and unchanged tasks are left as they are.
 * 
 * <p>
 * If the state has changed and the schedule was received from the server, save it to disk
 * so it can be recovered in case of a crash. 
 * 
 * @param newTasks List of MeasurementTasks from the server
 * @param reLoad if it's True, we're loading from disk: don't adjust frequencies or save to disk again.
 */
private void updateSchedule(List<MeasurementTask> newTasks, boolean reLoad) {

    // Keep track of what tasks need to be added.
    // Altered tasks are removed and then added, so they go here too
    Vector<MeasurementTask> tasksToAdd = new Vector<MeasurementTask>();

    // Keep track of what keys are not being used. Remove keys from this as
    // you find they are in use.
    Set<String> missingKeys = new HashSet<String>(currentSchedule.keySet());
    Set<String> keysToRemove = new HashSet<String>();

    Logger.i("Attempting to add new tasks");

    for (MeasurementTask newTask : newTasks) {

        // Adjust the frequency of the new task, based on the selected data consumption profile,
        // or ignore it if the task is disabled for this profile.
        // If we are loading again, don't re-adjust task frequencies.
        if (!reLoad) {
            if (!adjustInterval(newTask)) {
                continue;
            }
        }

        String newKey = newTask.getDescription().key;
        if (!missingKeys.contains(newKey)) {
            tasksToAdd.add(newTask);
        } else {
            // check for changes. If any parameter changes, it counts as a change.
            if (!currentSchedule.get(newKey).getDescription().equals(newTask.getDescription())) {
                // If there's a change, replace the task with the new task from the server
                keysToRemove.add(newKey);
                tasksToAdd.add(newTask);
            }
            // We've seen the task
            missingKeys.remove(newKey);
        }
    }

    // scheduleKeys now contain all keys that do not exist
    keysToRemove.addAll(missingKeys);

    // Add all new tasks, and copy all unmodified tasks, to a new queue.
    // Also update currentSchedule accordingly.
    PriorityBlockingQueue<MeasurementTask> newQueue = new PriorityBlockingQueue<MeasurementTask>(
            Config.MAX_TASK_QUEUE_SIZE, new TaskComparator());

    synchronized (currentSchedule) {
        Logger.i("Tasks to remove:" + keysToRemove.size());
        for (MeasurementTask task : this.taskQueue) {
            String taskKey = task.getDescription().key;
            if (!keysToRemove.contains(taskKey)) {
                newQueue.add(task);
            } else {
                Logger.w("Removing task with key" + taskKey);
                // Also need to keep our master schedule up to date
                currentSchedule.remove(taskKey);
            }
        }
        this.taskQueue = newQueue;
        // add all new tasks
        Logger.i("New tasks added:" + tasksToAdd.size());
        for (MeasurementTask task : tasksToAdd) {
            submitTask(task);
            currentSchedule.put(task.getDescription().key, task);
        }
    }

    if (!reLoad && (!tasksToAdd.isEmpty() || !keysToRemove.isEmpty())) {
        saveSchedulerState();
    }
}