Example usage for java.lang Thread NORM_PRIORITY

List of usage examples for java.lang Thread NORM_PRIORITY

Introduction

In this page you can find the example usage for java.lang Thread NORM_PRIORITY.

Prototype

int NORM_PRIORITY

To view the source code for java.lang Thread NORM_PRIORITY.

Click Source Link

Document

The default priority that is assigned to a thread.

Usage

From source file:helma.framework.core.Application.java

/**
 *  Create and start scheduler and cleanup thread
 *///  w  ww . j a v  a  2  s .c om
public synchronized void start() {
    starttime = System.currentTimeMillis();

    // as first thing, invoke global onStart() function
    RequestEvaluator eval = null;
    try {
        eval = getEvaluator();
        eval.invokeInternal(null, "onStart", RequestEvaluator.EMPTY_ARGS);
    } catch (Exception xcept) {
        logError("Error in " + name + ".onStart()", xcept);
    } finally {
        releaseEvaluator(eval);
    }

    worker = new Thread(this, name + "-worker");
    worker.setPriority(Thread.NORM_PRIORITY + 1);
    worker.start();
}

From source file:de.juwimm.cms.gui.admin.PanUnitGroupPerUser.java

public void actionPerformed(ActionEvent ae) {
    if (ae.getActionCommand().equals(Constants.ACTION_CHANGE_USERACCOUNTS)) {
        Thread t = new Thread(new Runnable() {
            public void run() {
                reload();//from  w w w. jav  a 2s . c o  m
            }
        });
        t.setPriority(Thread.NORM_PRIORITY);
        t.start();
    }
}

From source file:org.apache.cocoon.thread.impl.DefaultThreadPool.java

private void initPriority() {
    // Use priority from factory when changed
    priority = (factory.getPriority() != Thread.NORM_PRIORITY ? factory.getPriority() : priority);
    factory.setPriority(priority);/*from   w  w  w  . j  ava 2 s .c  o  m*/
}

From source file:com.petpet.c3po.controller.Controller.java

/**
 * Starts all the workers. Including the adaptors, consolidators and gatherer.
 *
 * @param collection//from w  w w.  j  a va2 s. c  o  m
 *          the name of the collection that is processed.
 * @param adaptThreads
 *          the number of adaptor threads in the pool.
 * @param consThreads
 *          the number of consolidator threads in the pool.
 * @param type
 *          the type of the adaptors.
 * @param adaptorcnf
 *          the adaptor configuration.
 */
private void startWorkers(String collection, int adaptThreads, int consThreads, String type,
        Map<String, String> adaptorcnf) {

    this.adaptorPool = Executors.newFixedThreadPool(adaptThreads);
    this.consolidatorPool = Executors.newFixedThreadPool(consThreads);

    List<Consolidator> consolidators = new ArrayList<Consolidator>();

    LOG.debug("Initializing consolidators...");
    for (int i = 0; i < consThreads; i++) {
        Consolidator c = new Consolidator(this.persistence, this.processingQueue);
        consolidators.add(c);
        this.consolidatorPool.submit(c);
    }

    // no more consolidators can be added.
    this.consolidatorPool.shutdown();

    List<ProcessingRule> rules = this.getRules(collection);

    Collections.sort(rules, new Comparator<ProcessingRule>() {

        // sorts from descending
        @Override
        public int compare(ProcessingRule r1, ProcessingRule r2) {
            int first = this.fixPriority(r2.getPriority());
            int second = this.fixPriority(r1.getPriority());
            return new Integer(first).compareTo(new Integer(second));
        }

        private int fixPriority(int prio) {
            if (prio < 0)
                return 0;

            if (prio > 1000)
                return 1000;

            return prio;
        }

    });

    LOG.debug("Initializing adaptors...");
    for (int i = 0; i < adaptThreads; i++) {
        AbstractAdaptor a = this.getAdaptor(type);

        a.setCache(this.persistence.getCache());
        a.setQueue(this.processingQueue);
        a.setGatherer(this.gatherer);
        a.setConfig(adaptorcnf);
        a.setRules(rules);
        a.configure();

        this.adaptorPool.submit(a);
    }

    // no more adaptors can be added.
    this.adaptorPool.shutdown();

    Thread gathererThread = new Thread(this.gatherer, "MetadataGatherer");
    gathererThread.setPriority(Thread.NORM_PRIORITY + 1);
    gathererThread.start();

    try {

        // kills the pool and all adaptor workers after a month;
        boolean adaptorsTerminated = this.adaptorPool.awaitTermination(2678400, TimeUnit.SECONDS);

        if (adaptorsTerminated) {
            this.stopConsoldators(consolidators);
            this.consolidatorPool.awaitTermination(2678400, TimeUnit.SECONDS);

        } else {
            System.out.println("Oh my, It seems something went wrong. This process took too long");
            LOG.error("Time out occurred, process was terminated");
        }

    } catch (InterruptedException e) {
        LOG.error("An error occurred: {}", e.getMessage());
    } finally {
        String path = FileUtils.getTempDirectory().getPath() + File.separator + "c3poarchives";
        FileUtils.deleteQuietly(new File(path));
    }

    // allow every rule to execute its tasks after job handling is done, like
    // printing statistics or cleaning up
    for (ProcessingRule processingRule : rules) {
        processingRule.onCommandFinished();
    }

    ActionLog log = new ActionLog(collection, ActionLog.UPDATED_ACTION);
    new ActionLogHelper(this.persistence).recordAction(log);
}

From source file:org.parosproxy.paros.model.Session.java

/**
 * Asynchronous call to save a session./*from  w w w .j  av a2s .  co m*/
 * @param fileName
 * @param callback
 */
protected void save(final String fileName, final SessionListener callback) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            Exception thrownException = null;
            try {
                save(fileName);
            } catch (Exception e) {
                // ZAP: Log exceptions
                log.warn(e.getMessage(), e);
                thrownException = e;
            }
            if (callback != null) {
                callback.sessionSaved(thrownException);
            }
        }
    });
    t.setPriority(Thread.NORM_PRIORITY - 2);
    t.start();
}

From source file:org.sakaiproject.search.elasticsearch.BaseElasticSearchIndexBuilder.java

/**
 * Searches for any docs in the search index that have not been indexed yet,
 * digests the content and loads it into the index.  Any docs with empty content will be removed from
 * the index.//from  w  w w . ja va 2s .  co  m
 */
protected void processContentQueue() {
    startTime = System.currentTimeMillis();

    // If there are a lot of docs queued up this could take awhile we don't want
    // to eat up all the CPU cycles.
    Thread.currentThread().setPriority(Thread.NORM_PRIORITY - 1);

    if (getPendingDocuments() == 0) {
        getLog().trace("No pending docs for index builder [" + getName() + "]");
        return;
    }

    SearchResponse response = findContentQueue();

    SearchHit[] hits = response.getHits().hits();
    List<NoContentException> noContentExceptions = new ArrayList();
    getLog().debug(getPendingDocuments() + " pending docs for index builder [" + getName() + "]");

    BulkRequestBuilder bulkRequest = newContentQueueBulkUpdateRequestBuilder();

    for (SearchHit hit : hits) {

        if (bulkRequest.numberOfActions() < bulkRequestSize) {
            try {
                processContentQueueEntry(hit, bulkRequest);
            } catch (NoContentException e) {
                noContentExceptions.add(e);
            }
        } else {
            executeBulkRequest(bulkRequest);
            bulkRequest = newContentQueueBulkUpdateRequestBuilder();
        }
    }

    // execute any remaining bulks requests not executed yet
    if (bulkRequest.numberOfActions() > 0) {
        executeBulkRequest(bulkRequest);
    }

    // remove any docs without content, so we don't try to index them again
    if (!noContentExceptions.isEmpty()) {
        for (NoContentException noContentException : noContentExceptions) {
            deleteDocument(noContentException);
        }
    }

    lastLoad = System.currentTimeMillis();

    if (hits.length > 0) {
        getLog().info("Finished indexing " + hits.length + " docs in " + ((lastLoad - startTime))
                + " ms for index builder " + getName());
    }

}

From source file:com.ccxt.whl.DemoApplication.java

/** ?ImageLoader */
public static void initImageLoader(Context context) {
    File cacheDir = StorageUtils.getOwnCacheDirectory(context, Constant.CACHE_DIR_IMAGE);// ??
    Log.d("cacheDir" + cacheDir.getPath());
    // ?ImageLoader(?,?)?APPLACATION???
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
            // ?/*from w w  w .j  ava2  s  .co m*/
            .threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 2).memoryCache(new WeakMemoryCache())
            .denyCacheImageMultipleSizesInMemory()
            /****** /
            .memoryCache(new LruMemoryCache(2 * 1024 * 1024))  
              .memoryCacheSize(2 * 1024 * 1024)  
              .memoryCacheSizePercentage(13) // default  
              /***end***/
            .discCacheFileNameGenerator(new Md5FileNameGenerator())
            // ?URI??MD5 
            .tasksProcessingOrder(QueueProcessingType.LIFO).discCache(new UnlimitedDiscCache(cacheDir))// 
            // .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
            .writeDebugLogs() // Remove for release app
            .build();
    // Initialize ImageLoader with configuration.
    ImageLoader.getInstance().init(config);// ??
}

From source file:org.parosproxy.paros.model.Session.java

/**
 * Asynchronous call to snapshot a session.
 * @param fileName/*w  w w.  ja v  a 2  s  . c om*/
 * @param callback
 */
protected void snapshot(final String fileName, final SessionListener callback) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            Exception thrownException = null;
            try {
                snapshot(fileName);
            } catch (Exception e) {
                // ZAP: Log exceptions
                log.warn(e.getMessage(), e);
                thrownException = e;
            }
            if (callback != null) {
                callback.sessionSnapshot(thrownException);
            }
        }
    });
    t.setPriority(Thread.NORM_PRIORITY - 2);
    t.start();
}

From source file:org.sakaiproject.search.elasticsearch.ElasticSearchIndexBuilder.java

/**
 * Searches for any docs in the search index that have not been indexed yet,
 * digests the content and loads it into the index.  Any docs with empty content will be removed from
 * the index.//ww  w .ja v  a 2s .co m
 */
public void processContentQueue() {
    startTime = System.currentTimeMillis();

    // If there are a lot of docs queued up this could take awhile we don't want
    // to eat up all the CPU cycles.
    Thread.currentThread().setPriority(Thread.NORM_PRIORITY - 1);

    if (getPendingDocuments() == 0) {
        log.trace("no pending docs.");
        return;
    }

    SearchResponse response = client.prepareSearch(indexName).setQuery(matchAllQuery())
            .setTypes(ElasticSearchService.SAKAI_DOC_TYPE)
            .setPostFilter(orFilter(missingFilter(SearchService.FIELD_INDEXED),
                    termFilter(SearchService.FIELD_INDEXED, false)))
            .setSize(contentIndexBatchSize).addFields(SearchService.FIELD_REFERENCE, SearchService.FIELD_SITEID)
            .execute().actionGet();

    SearchHit[] hits = response.getHits().hits();
    List<NoContentException> noContentExceptions = new ArrayList();
    log.debug(getPendingDocuments() + " pending docs.");

    BulkRequestBuilder bulkRequest = client.prepareBulk();

    for (SearchHit hit : hits) {

        if (bulkRequest.numberOfActions() < bulkRequestSize) {
            String reference = getFieldFromSearchHit(SearchService.FIELD_REFERENCE, hit);
            String siteId = getFieldFromSearchHit(SearchService.FIELD_SITEID, hit);

            EntityContentProducer ecp = getContentProducerForReference(reference);

            if (ecp != null) {
                //updating was causing issues without a _source, so doing delete and re-add
                try {
                    deleteDocument(hit.getId(), siteId);
                    bulkRequest.add(prepareIndex(reference, ecp, true));
                } catch (NoContentException e) {
                    noContentExceptions.add(new NoContentException(hit.getId(), reference, siteId));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            } else {
                // if there is no content to index remove the doc, its pointless to have it included in the index
                // and we will just waste cycles looking at it again everytime this thread runs, and will probably
                // never finish because of it.
                noContentExceptions.add(new NoContentException(hit.getId(), reference, siteId));

            }

        } else {
            executeBulkRequest(bulkRequest);
            bulkRequest = client.prepareBulk();
        }
    }

    // execute any remaining bulks requests not executed yet
    if (bulkRequest.numberOfActions() > 0) {
        executeBulkRequest(bulkRequest);
    }

    // remove any docs without content, so we don't try to index them again
    if (!noContentExceptions.isEmpty()) {
        for (NoContentException noContentException : noContentExceptions) {
            deleteDocument(noContentException);
        }
    }

    lastLoad = System.currentTimeMillis();

    if (hits.length > 0) {
        log.info("Finished indexing " + hits.length + " docs in " + ((lastLoad - startTime)) + " ms");
    }

}

From source file:com.nmote.smpp.Session.java

private void requestReceived(AbstractPDU pdu) {
    final Command command = new Command(pdu);

    // Execute Command
    if (executor != null) {
        executor.exec(new Runnable() {
            @Override/*from   ww  w. ja va 2  s.c o m*/
            public void run() {
                try {
                    processIncomingCommand(command);
                } catch (Throwable t) {
                    log.error("Processing incoming command failed", t);
                }
            }
        }, Thread.NORM_PRIORITY);
    } else {
        processIncomingCommand(command);
    }
}