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:org.xwiki.search.solr.internal.DefaultSolrIndexer.java

@Override
public void initialize() throws InitializationException {
    // Initialize the queues before starting the threads.
    this.resolveQueue = new LinkedBlockingQueue<ResolveQueueEntry>();
    this.indexQueue = new LinkedBlockingQueue<IndexQueueEntry>(this.configuration.getIndexerQueueCapacity());

    // Launch the resolve thread
    this.resolveThread = new Thread(new Resolver());
    this.resolveThread.setName("XWiki Solr resolve thread");
    this.resolveThread.setDaemon(true);
    this.resolveThread.start();
    this.resolveThread.setPriority(Thread.NORM_PRIORITY - 1);

    // Launch the index thread
    this.indexThread = new Thread(this);
    this.indexThread.setName("XWiki Solr index thread");
    this.indexThread.setDaemon(true);
    this.indexThread.start();
    this.indexThread.setPriority(Thread.NORM_PRIORITY - 1);

    // Setup indexer job thread
    BasicThreadFactory factory = new BasicThreadFactory.Builder().namingPattern("XWiki Solr index job thread")
            .daemon(true).priority(Thread.MIN_PRIORITY).build();
    this.indexerJobs = Executors.newSingleThreadExecutor(factory);
}

From source file:com.alibaba.wasp.master.AssignmentManager.java

/**
 * Get a named {@link java.util.concurrent.ThreadFactory} that just builds daemon threads
 *
 * @param prefix//from  ww w .  ja  v  a2s. c  om
 *          name prefix for all threads created from the factory
 * @return a thread factory that creates named, daemon threads
 */
private static ThreadFactory newDaemonThreadFactory(final String prefix) {
    final ThreadFactory namedFactory = Threads.getNamedThreadFactory(prefix);
    return new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = namedFactory.newThread(r);
            if (!t.isDaemon()) {
                t.setDaemon(true);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    };
}

From source file:com.univpm.s1055802.faceplusplustester.Main.java

/**
 * Inizializza la libreria Universal Image Loadeer
 *///from w w w. j  a v a  2s  . c  om
private void initUIL() {

    // Create configuration for ImageLoader (all options are optional)
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 2).memoryCacheSize(1500000) // 1.5 Mb
            .denyCacheImageMultipleSizesInMemory().discCacheFileNameGenerator(new Md5FileNameGenerator())
            .build();

    // Get singletone instance of ImageLoader
    // Initialize ImageLoader with created configuration. Do it once.
    ImageLoader.getInstance().init(config);
}

From source file:org.fdroid.fdroid.FDroidApp.java

@TargetApi(9)
@Override//from w  w w . j a  va  2  s. com
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT >= 9 && BuildConfig.DEBUG) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    }
    updateLanguage();
    ACRA.init(this);

    // Needs to be setup before anything else tries to access it.
    // Perhaps the constructor is a better place, but then again,
    // it is more deterministic as to when this gets called...
    Preferences.setup(this);
    curTheme = Preferences.get().getTheme();

    // Apply the Google PRNG fixes to properly seed SecureRandom
    PRNGFixes.apply();

    // Check that the installed app cache hasn't gotten out of sync somehow.
    // e.g. if we crashed/ran out of battery half way through responding
    // to a package installed intent. It doesn't really matter where
    // we put this in the bootstrap process, because it runs on a different
    // thread, which will be delayed by some seconds to avoid an error where
    // the database is locked due to the database updater.
    InstalledAppCacheUpdater.updateInBackground(getApplicationContext());

    // make sure the current proxy stuff is configured
    Preferences.get().configureProxy();

    // If the user changes the preference to do with filtering rooted apps,
    // it is easier to just notify a change in the app provider,
    // so that the newly updated list will correctly filter relevant apps.
    Preferences.get().registerAppsRequiringRootChangeListener(new Preferences.ChangeListener() {
        @Override
        public void onPreferenceChange() {
            getContentResolver().notifyChange(AppProvider.getContentUri(), null);
        }
    });

    // This is added so that the bluetooth:// scheme we use for URLs the BluetoothDownloader
    // understands is not treated as invalid by the java.net.URL class. The actual Handler does
    // nothing, but its presence is enough.
    URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
        @Override
        public URLStreamHandler createURLStreamHandler(String protocol) {
            return TextUtils.equals(protocol, "bluetooth") ? new Handler() : null;
        }
    });

    final Context context = this;
    Preferences.get().registerUnstableUpdatesChangeListener(new Preferences.ChangeListener() {
        @Override
        public void onPreferenceChange() {
            AppProvider.Helper.calcDetailsFromIndex(context);
        }
    });

    // Clear cached apk files. We used to just remove them after they'd
    // been installed, but this causes problems for proprietary gapps
    // users since the introduction of verification (on pre-4.2 Android),
    // because the install intent says it's finished when it hasn't.
    if (!Preferences.get().shouldCacheApks()) {
        Utils.deleteFiles(Utils.getApkCacheDir(this), null, ".apk");
    }

    // Index files which downloaded, but were not removed (e.g. due to F-Droid being force
    // closed during processing of the file, before getting a chance to delete). This may
    // include both "index-*-downloaded" and "index-*-extracted.xml" files. The first is from
    // either signed or unsigned repos, and the later is from signed repos.
    Utils.deleteFiles(getCacheDir(), "index-", null);

    // As above, but for legacy F-Droid clients that downloaded under a different name, and
    // extracted to the files directory rather than the cache directory.
    // TODO: This can be removed in a a few months or a year (e.g. 2016) because people will
    // have upgraded their clients, this code will have executed, and they will not have any
    // left over files any more. Even if they do hold off upgrading until this code is removed,
    // the only side effect is that they will have a few more MiB of storage taken up on their
    // device until they uninstall and re-install F-Droid.
    Utils.deleteFiles(getCacheDir(), "dl-", null);
    Utils.deleteFiles(getFilesDir(), "index-", null);

    UpdateService.schedule(getApplicationContext());
    bluetoothAdapter = getBluetoothAdapter();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .imageDownloader(new IconDownloader(getApplicationContext()))
            .diskCache(new LimitedAgeDiskCache(
                    new File(StorageUtils.getCacheDirectory(getApplicationContext(), true), "icons"), null,
                    new FileNameGenerator() {
                        @Override
                        public String generate(String imageUri) {
                            return imageUri.substring(imageUri.lastIndexOf('/') + 1);
                        }
                    },
                    // 30 days in secs: 30*24*60*60 = 2592000
                    2592000))
            .threadPoolSize(4).threadPriority(Thread.NORM_PRIORITY - 2) // Default is NORM_PRIORITY - 1
            .build();
    ImageLoader.getInstance().init(config);

    // TODO reintroduce PinningTrustManager and MemorizingTrustManager

    // initialized the local repo information
    FDroidApp.initWifiSettings();
    startService(new Intent(this, WifiStateChangeService.class));
    // if the HTTPS pref changes, then update all affected things
    Preferences.get().registerLocalRepoHttpsListeners(new ChangeListener() {
        @Override
        public void onPreferenceChange() {
            startService(new Intent(FDroidApp.this, WifiStateChangeService.class));
        }
    });

    configureTor(Preferences.get().isTorEnabled());
}

From source file:org.jumpmind.symmetric.service.impl.NodeCommunicationService.java

protected ThreadPoolExecutor getExecutor(final CommunicationType communicationType) {
    ThreadPoolExecutor service = executors.get(communicationType);

    String threadCountParameter = "";
    switch (communicationType) {
    case PULL://from w  w  w .  ja v  a2  s .  co m
        threadCountParameter = ParameterConstants.PULL_THREAD_COUNT_PER_SERVER;
        break;
    case PUSH:
        threadCountParameter = ParameterConstants.PUSH_THREAD_COUNT_PER_SERVER;
        break;
    case FILE_PULL:
        threadCountParameter = ParameterConstants.FILE_PUSH_THREAD_COUNT_PER_SERVER;
        break;
    case FILE_PUSH:
        threadCountParameter = ParameterConstants.FILE_PUSH_THREAD_COUNT_PER_SERVER;
        break;
    case EXTRACT:
        threadCountParameter = ParameterConstants.INITIAL_LOAD_EXTRACT_THREAD_COUNT_PER_SERVER;
        break;
    default:
        break;
    }
    int threadCount = parameterService.getInt(threadCountParameter, 1);

    if (service != null && service.getCorePoolSize() != threadCount) {
        log.info("{} has changed from {} to {}.  Restarting thread pool",
                new Object[] { threadCountParameter, service.getCorePoolSize(), threadCount });
        stop();
        service = null;
    }

    if (service == null) {
        synchronized (this) {
            service = executors.get(communicationType);
            if (service == null) {
                if (threadCount <= 0) {
                    log.warn("{}={} is not a valid value. Defaulting to 1", threadCountParameter, threadCount);
                    threadCount = 1;
                } else if (threadCount > 1) {
                    log.info("{} will use {} threads", communicationType.name().toLowerCase(), threadCount);
                }
                service = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadCount, new ThreadFactory() {
                    final AtomicInteger threadNumber = new AtomicInteger(1);
                    final String namePrefix = parameterService.getEngineName().toLowerCase() + "-"
                            + communicationType.name().toLowerCase() + "-";

                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setName(namePrefix + threadNumber.getAndIncrement());
                        if (t.isDaemon()) {
                            t.setDaemon(false);
                        }
                        if (t.getPriority() != Thread.NORM_PRIORITY) {
                            t.setPriority(Thread.NORM_PRIORITY);
                        }
                        return t;
                    }
                });
                executors.put(communicationType, service);
            }
        }
    }
    return service;
}

From source file:com.vanisty.ui.MenuActivity.java

public void initializeImageLoader() {
    File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "Eventproject/Cache");

    // Get singletone instance of ImageLoader
    imageLoader = ImageLoader.getInstance();
    // Create configuration for ImageLoader (all options are optional, use only those you really want to customize)
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .memoryCacheExtraOptions(480, 800) // max width, max height
            .threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 1).denyCacheImageMultipleSizesInMemory()
            .offOutOfMemoryHandling().memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation
            .discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
            .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
            .imageDownloader(new URLConnectionImageDownloader(8 * 1000, 20 * 1000)) // connectTimeout (8 s), readTimeout (20 s)
            .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
            //.enableLogging()
            .build();//  w w  w  .  ja  va  2 s  . c  o  m
    // Initialize ImageLoader with created configuration. Do it once on Application start.
    imageLoader.init(config);

}

From source file:org.parosproxy.paros.extension.history.ManualRequestEditorDialog.java

private void send(final HttpMessage msg) {
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                getHttpSender().sendAndReceive(msg, getChkFollowRedirect().isSelected());

                EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        if (!msg.getResponseHeader().isEmpty()) {
                            getResponsePanel().setMessage(msg, false);

                            final int finalType = HistoryReference.TYPE_MANUAL;
                            Thread t = new Thread(new Runnable() {
                                public void run() {
                                    addHistory(msg, finalType);
                                }//  ww w.j av a2  s. c  om
                            });
                            t.start();

                        }
                        getPanelTab().setSelectedIndex(1);
                    }
                });

            } catch (NullPointerException npe) {
                getExtention().getView().showWarningDialog("Malformed header error.");
            } catch (HttpMalformedHeaderException mhe) {
                getExtention().getView().showWarningDialog("Malformed header error.");
            } catch (IOException ioe) {
                getExtention().getView().showWarningDialog("IO error in sending request.");
            } catch (Exception e) {
                // ZAP: Log exceptions
                log.warn(e.getMessage(), e);
            } finally {
                btnSend.setEnabled(true);
            }
        }
    });

    t.setPriority(Thread.NORM_PRIORITY);
    t.start();
}

From source file:com.jtechme.apphub.FDroidApp.java

@TargetApi(9)
@Override//from  w  w w. j  a  v  a 2s. c  om
public void onCreate() {
    if (Build.VERSION.SDK_INT >= 9 && BuildConfig.DEBUG) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    }
    updateLanguage();
    super.onCreate();
    ACRA.init(this);

    // Needs to be setup before anything else tries to access it.
    // Perhaps the constructor is a better place, but then again,
    // it is more deterministic as to when this gets called...
    Preferences.setup(this);

    // Apply the Google PRNG fixes to properly seed SecureRandom
    PRNGFixes.apply();

    // Check that the installed app cache hasn't gotten out of sync somehow.
    // e.g. if we crashed/ran out of battery half way through responding
    // to a package installed intent. It doesn't really matter where
    // we put this in the bootstrap process, because it runs on a different
    // thread, which will be delayed by some seconds to avoid an error where
    // the database is locked due to the database updater.
    InstalledAppCacheUpdater.updateInBackground(getApplicationContext());

    // If the user changes the preference to do with filtering rooted apps,
    // it is easier to just notify a change in the app provider,
    // so that the newly updated list will correctly filter relevant apps.
    Preferences.get().registerAppsRequiringRootChangeListener(new Preferences.ChangeListener() {
        @Override
        public void onPreferenceChange() {
            getContentResolver().notifyChange(AppProvider.getContentUri(), null);
        }
    });

    // This is added so that the bluetooth:// scheme we use for URLs the BluetoothDownloader
    // understands is not treated as invalid by the java.net.URL class. The actual Handler does
    // nothing, but its presence is enough.
    URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
        @Override
        public URLStreamHandler createURLStreamHandler(String protocol) {
            return TextUtils.equals(protocol, "bluetooth") ? new Handler() : null;
        }
    });

    final Context context = this;
    Preferences.get().registerUnstableUpdatesChangeListener(new Preferences.ChangeListener() {
        @Override
        public void onPreferenceChange() {
            AppProvider.Helper.calcDetailsFromIndex(context);
        }
    });

    // Clear cached apk files. We used to just remove them after they'd
    // been installed, but this causes problems for proprietary gapps
    // users since the introduction of verification (on pre-4.2 Android),
    // because the install intent says it's finished when it hasn't.
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    curTheme = Theme.valueOf(prefs.getString(Preferences.PREF_THEME, Preferences.DEFAULT_THEME));
    Utils.deleteFiles(Utils.getApkDownloadDir(this), null, ".apk");
    if (!Preferences.get().shouldCacheApks()) {
        Utils.deleteFiles(Utils.getApkCacheDir(this), null, ".apk");
    }

    // Index files which downloaded, but were not removed (e.g. due to F-Droid being force
    // closed during processing of the file, before getting a chance to delete). This may
    // include both "index-*-downloaded" and "index-*-extracted.xml" files. The first is from
    // either signed or unsigned repos, and the later is from signed repos.
    Utils.deleteFiles(getCacheDir(), "index-", null);

    // As above, but for legacy F-Droid clients that downloaded under a different name, and
    // extracted to the files directory rather than the cache directory.
    // TODO: This can be removed in a a few months or a year (e.g. 2016) because people will
    // have upgraded their clients, this code will have executed, and they will not have any
    // left over files any more. Even if they do hold off upgrading until this code is removed,
    // the only side effect is that they will have a few more MiB of storage taken up on their
    // device until they uninstall and re-install F-Droid.
    Utils.deleteFiles(getCacheDir(), "dl-", null);
    Utils.deleteFiles(getFilesDir(), "index-", null);

    UpdateService.schedule(getApplicationContext());
    bluetoothAdapter = getBluetoothAdapter();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .imageDownloader(new IconDownloader(getApplicationContext()))
            .diskCache(new LimitedAgeDiskCache(
                    new File(StorageUtils.getCacheDirectory(getApplicationContext(), true), "icons"), null,
                    new FileNameGenerator() {
                        @Override
                        public String generate(String imageUri) {
                            return imageUri.substring(imageUri.lastIndexOf('/') + 1);
                        }
                    },
                    // 30 days in secs: 30*24*60*60 = 2592000
                    2592000))
            .threadPoolSize(4).threadPriority(Thread.NORM_PRIORITY - 2) // Default is NORM_PRIORITY - 1
            .build();
    ImageLoader.getInstance().init(config);

    // TODO reintroduce PinningTrustManager and MemorizingTrustManager

    // initialized the local repo information
    FDroidApp.initWifiSettings();
    startService(new Intent(this, WifiStateChangeService.class));
    // if the HTTPS pref changes, then update all affected things
    Preferences.get().registerLocalRepoHttpsListeners(new ChangeListener() {
        @Override
        public void onPreferenceChange() {
            startService(new Intent(FDroidApp.this, WifiStateChangeService.class));
        }
    });
}

From source file:org.apache.lens.server.LensServices.java

public synchronized void start() {
    if (getServiceState() != STATE.STARTED) {
        super.start();
    }/* ww  w . ja  v a 2s.co  m*/

    if (!isServerStatePersistenceEnabled) {
        log.info("Server restart is not enabled. Not persisting lens server state");
    } else {
        ThreadFactory factory = new BasicThreadFactory.Builder()
                .namingPattern("Lens-server-snapshotter-Thread-%d").daemon(true).priority(Thread.NORM_PRIORITY)
                .build();
        serverSnapshotScheduler = Executors.newSingleThreadScheduledExecutor(factory);
        serverSnapshotScheduler.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                try {
                    final String runId = UUID.randomUUID().toString();
                    logSegregationContext.setLogSegregationId(runId);
                    persistLensServiceState();
                    log.info("SnapShot of Lens Services created");
                } catch (Exception e) {
                    incrCounter(SERVER_STATE_PERSISTENCE_ERRORS);
                    log.error("Unable to persist lens server state", e);
                }
            }
        }, serverStatePersistenceInterval, serverStatePersistenceInterval, TimeUnit.MILLISECONDS);
        log.info("Enabled periodic persistence of lens server state at {} millis interval",
                serverStatePersistenceInterval);
    }
}

From source file:com.amazon.mws.shared.MwsConnection.java

/**
 * Get the shared executor service that is used by async calls if no
 * executor is supplied.//from w  ww . j a  v a 2  s  .c o m
 * 
 * @return The shared executor service.
 */
private ExecutorService getSharedES() {
    synchronized (this.getClass()) {
        if (sharedES != null) {
            return sharedES;
        }
        sharedES = new ThreadPoolExecutor(maxAsyncThreads / 10, maxAsyncThreads, 60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(maxAsyncQueueSize), new ThreadFactory() {
                    private final AtomicInteger threadNumber = new AtomicInteger(1);

                    public Thread newThread(Runnable task) {
                        Thread thread = new Thread(task, "MWSClient-" + threadNumber.getAndIncrement());
                        thread.setDaemon(true);
                        thread.setPriority(Thread.NORM_PRIORITY);
                        return thread;
                    }
                }, new RejectedExecutionHandler() {
                    public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
                        if (!executor.isShutdown()) {
                            log.warn("MWSClient async queue full, running on calling thread.");
                            task.run();
                        } else {
                            throw new RejectedExecutionException();
                        }
                    }
                });
        return sharedES;
    }
}