Example usage for java.lang Thread MAX_PRIORITY

List of usage examples for java.lang Thread MAX_PRIORITY

Introduction

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

Prototype

int MAX_PRIORITY

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

Click Source Link

Document

The maximum priority that a thread can have.

Usage

From source file:org.zenoss.zep.index.impl.lucene.LuceneEventIndexBackend.java

private synchronized void startReopenThread() {
    stopReopenThread();/*from  www . ja  va 2s  . c  o  m*/
    logger.debug("Starting NRT Reopen Thread");
    // Max = min on this because min only matters when you call
    // waitForGeneration() on the NRTManager, which we never do
    this.nrtManagerReopenThread = new ControlledRealTimeReopenThread<IndexSearcher>(this.trackingIndexWriter,
            this.searcherManager, this.readerReopenInterval, this.readerReopenInterval);
    this.nrtManagerReopenThread.setName(name + "NRT Reopen Thread");
    this.nrtManagerReopenThread
            .setPriority(Math.min(Thread.currentThread().getPriority() + 2, Thread.MAX_PRIORITY));
    this.nrtManagerReopenThread.setDaemon(true);
    this.nrtManagerReopenThread.start();
}

From source file:net.gleamynode.oil.impl.wal.store.FileLogStore.java

private void parseProperties() {
    String file;/*from w w  w  . j  a v a 2s.c o m*/
    int maxItemSize;
    int bufferFlushInterval;
    int bufferSize;
    String threadName;
    int threadPriority;

    // file
    file = properties.getProperty(FileLogStoreConstants.PROP_FILE);

    if (file == null) {
        throw new IllegalPropertyException();
    }

    // maxItemSize
    String value = properties.getProperty(FileLogStoreConstants.PROP_MAX_ITEM_SIZE,
            String.valueOf(FileLogStoreConstants.DEFAULT_MAX_ITEM_SIZE));

    try {
        maxItemSize = Integer.parseInt(value);
    } catch (Exception e) {
        throw new IllegalPropertyException(e);
    }

    if (maxItemSize <= 0) {
        throw new IllegalPropertyException();
    }

    // bufferFlushInterval
    value = properties.getProperty(FileLogStoreConstants.PROP_BUFFER_FLUSH_INTERVAL,
            String.valueOf(FileLogStoreConstants.DEFAULT_BUFFER_FLUSH_INTERVAL));

    try {
        bufferFlushInterval = Integer.parseInt(value);
    } catch (Exception e) {
        throw new IllegalPropertyException(e);
    }

    if (bufferFlushInterval < 1) {
        throw new IllegalPropertyException();
    }

    // bufferSize
    value = properties.getProperty(FileLogStoreConstants.PROP_BUFFER_SIZE,
            String.valueOf(FileLogStoreConstants.DEFAULT_BUFFER_SIZE));

    try {
        bufferSize = Integer.parseInt(value);
    } catch (Exception e) {
        throw new IllegalPropertyException(e);
    }

    if (bufferSize < 1) {
        throw new IllegalPropertyException();
    }

    // threadName
    threadName = properties
            .getProperty(FileLogStoreConstants.PROP_THREAD_NAME, FileLogStoreConstants.DEFAULT_THREAD_NAME)
            .trim();

    if (threadName.length() == 0) {
        throw new IllegalPropertyException();
    }

    // threadPriority
    value = properties.getProperty(FileLogStoreConstants.PROP_THREAD_PRIORITY,
            String.valueOf(FileLogStoreConstants.DEFAULT_THREAD_PRIORITY));

    try {
        threadPriority = Integer.parseInt(value);
    } catch (Exception e) {
        throw new IllegalPropertyException(e);
    }

    if ((threadPriority < Thread.MIN_PRIORITY) || (threadPriority > Thread.MAX_PRIORITY)) {
        throw new IllegalPropertyException();
    }

    this.file = new File(file);
    this.maxItemSize = maxItemSize;
    this.bufferFlushInterval = bufferFlushInterval;
    this.bufferSize = bufferSize;
    this.threadName = threadName;
    this.threadPriority = threadPriority;
}

From source file:api.wiki.WikiNameApi2.java

private void processSpecific(String s, PeopleNameOption option, final ProgressCallback callback) {
    final TreeMap<String, String> values = getGenderNames(s);

    final float[] progressValues = ProgressUtil.getProgressValues(values.size());
    int counter = 1;

    for (final String peopleName : values.values()) {
        final int c = counter++;
        callback.onProgressUpdate(progressValues[c]);
        Task<Void> task = new Task<Void>() {
            @Override//w ww  . j  ava  2  s. c  o  m
            protected Void call() throws Exception {
                final File file = processName(peopleName, option);
                Platform.runLater(new Runnable() {

                    @Override
                    public void run() {
                        callback.onProgress(processFile(peopleName, file));
                    }
                });

                return null;
            }
        };
        Thread thread = new Thread(task);
        thread.setPriority(Thread.MAX_PRIORITY);
        thread.start();
    }
}

From source file:org.n52.ifgicopter.spf.SPFRegistry.java

/**
 * Initialize all registered modules.//from   ww  w .  ja  va 2 s.c  o  m
 * 
 * @throws ClassNotFoundException
 *         if the class to be reflected is not in the classpath.
 * @throws InstantiationException
 *         if the class to be reflected could not be instantiated.
 * @throws IllegalAccessException
 *         if the class to be reflected is not accessible
 */
private void initModules() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException e) {
        log.warn(e.getMessage(), e);
    } catch (InstantiationException e) {
        log.warn(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        log.warn(e.getMessage(), e);
    } catch (UnsupportedLookAndFeelException e) {
        log.warn(e.getMessage(), e);
    }

    SplashDialog splash = new SplashDialog();
    Thread t = new Thread(splash);
    t.setPriority(Thread.MAX_PRIORITY);
    t.start();

    this.modules = new ArrayList<IModule>();
    this.engine = new SPFEngine();
    this.mainFrame = new SPFMainFrame();
    this.engine.setMainFrame(this.mainFrame);
    this.engine.addPositionListener(this.mainFrame.getMapPanel());
    this.statusChangeListeners = new ArrayList<IStatusChangeListener>();
    this.outputMessageListeners = new ArrayList<IOutputMessageListener>();

    /*
     * IOutputPlugins
     */
    List<IOutputPlugin> oplugs = new ArrayList<IOutputPlugin>();

    String tmp = this.properties.getProperty(OUTPUT_PLUGINS_PROP);
    if (tmp == null)
        log.warn("No config parameter " + OUTPUT_PLUGINS_PROP + " given.");
    else {

        tmp = tmp.trim();
        String[] oplugins = tmp.split(LIST_SEPARATOR);
        String[] params = null;
        Class<?>[] paramsClassArray = null;

        if (!tmp.equals("")) {

            // int opCount = 1;
            for (String classString : oplugins) {
                classString = classString.trim();

                if (classString.length() == 0)
                    continue;

                /*
                 * do we have any parameters?
                 */
                int pos = classString.indexOf("(");
                if (pos > 0) {
                    params = classString.substring(pos + 1, classString.length() - 1).split(",");
                    paramsClassArray = new Class[params.length];
                    if (params.length > 0) {
                        for (int i = 0; i < params.length; i++) {
                            paramsClassArray[i] = String.class;
                            params[i] = params[i].trim();
                        }
                        classString = classString.substring(0, pos);
                    }
                }

                Class<?> clazz;
                try {
                    clazz = Class.forName(classString);
                } catch (ClassNotFoundException e) {
                    log.error(null, e);
                    continue;
                } catch (NoClassDefFoundError e) {
                    log.error(null, e);
                    continue;
                }

                try {
                    IOutputPlugin oplugin = null;

                    if (params != null && params.length > 0) {
                        Constructor<?> constructor = clazz.getConstructor(paramsClassArray);
                        oplugin = (IOutputPlugin) constructor.newInstance((Object[]) params);
                        params = null;
                        paramsClassArray = null;
                    } else {
                        try {
                            oplugin = ((IOutputPlugin) clazz.newInstance());
                        } catch (InstantiationException e) {
                            log.error(null, e);
                            continue;
                        }
                    }

                    oplugs.add(oplugin);

                } catch (IllegalAccessException e) {
                    log.error("Could not access class with name '" + classString + "'.", e);
                } catch (InstantiationException e) {
                    log.error("Could not instantiate class with name '" + classString + "'.", e);
                } catch (SecurityException e) {
                    log.error(null, e);
                } catch (NoSuchMethodException e) {
                    log.error(
                            "A constructor with "
                                    + ((paramsClassArray == null) ? "NULL"
                                            : Integer.valueOf(paramsClassArray.length))
                                    + " String arguments for Class " + clazz.getName() + " could not be found.",
                            e);
                } catch (IllegalArgumentException e) {
                    log.error(null, e);
                } catch (InvocationTargetException e) {
                    log.error(null, e);
                } catch (ClassCastException e) {
                    log.error(clazz.getName() + " is not an instance of IOutputPlugin! Could not instantiate.",
                            e);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }

                // opCount++;
            }
        } else
            log.warn(OUTPUT_PLUGINS_PROP + " is empty, no output plugins defined.");
    }

    /*
     * worker threadpool
     */
    this.threadPool = SPFThreadPool.getInstance();
    this.modules.add(this.threadPool);

    /*
     * IInputPlugins
     */
    List<IInputPlugin> iplugs = new ArrayList<IInputPlugin>();

    tmp = this.properties.getProperty(INPUT_PLUGINS_PROP);
    if (tmp == null) {
        log.warn("No config parameter " + INPUT_PLUGINS_PROP + " given.");
    } else {
        tmp = tmp.trim();
        String[] params = null;
        Class<?>[] paramsClassArray = null;
        String[] iplugins = tmp.split(LIST_SEPARATOR);

        if (!tmp.equals("")) {
            for (String classString : iplugins) {
                classString = classString.trim();

                if (classString.length() == 0)
                    continue;

                /*
                 * do we have any parameters?
                 */
                int pos = classString.indexOf("(");
                if (pos > 0) {
                    params = classString.substring(pos + 1, classString.length() - 1).split(",");
                    paramsClassArray = new Class[params.length];
                    if (params.length > 0) {
                        for (int i = 0; i < params.length; i++) {
                            paramsClassArray[i] = String.class;
                            params[i] = params[i].trim();
                        }
                        classString = classString.substring(0, pos);
                    }
                }

                Class<?> clazz;
                try {
                    clazz = Class.forName(classString);
                } catch (ClassNotFoundException e) {
                    log.error(null, e);
                    continue;
                } catch (NoClassDefFoundError e) {
                    log.error(null, e);
                    continue;
                }

                if (clazz != null) {
                    IInputPlugin iplugin = null;
                    if (pos > 0) {
                        try {
                            Constructor<?> constructor = clazz.getConstructor(paramsClassArray);
                            iplugin = (IInputPlugin) constructor.newInstance((Object[]) params);
                        } catch (IllegalAccessException e) {
                            log.error("Could not access class with name '" + classString + "'.", e);
                        } catch (InstantiationException e) {
                            log.error("Could not instantiate class with name '" + classString + "'.", e);
                        } catch (SecurityException e) {
                            log.error(null, e);
                        } catch (NoSuchMethodException e) {
                            log.error("A constructor with "
                                    + ((paramsClassArray == null) ? "NULL"
                                            : Integer.valueOf(paramsClassArray.length))
                                    + " String arguments for Class " + clazz.getName() + " could not be found.",
                                    e);
                        } catch (IllegalArgumentException e) {
                            log.error(null, e);
                        } catch (InvocationTargetException e) {
                            log.error(null, e);
                        } catch (ClassCastException e) {
                            log.error(clazz.getName()
                                    + " is not an instance of IInputPlugin! Could not instantiate.", e);
                        }

                        params = null;
                        paramsClassArray = null;
                    } else {
                        try {
                            iplugin = (IInputPlugin) clazz.newInstance();
                        } catch (InstantiationException e) {
                            log.error(null, e);
                            continue;
                        }
                    }
                    iplugs.add(iplugin);
                }
            }
        } else
            log.warn(INPUT_PLUGINS_PROP + " is empty, no input plugins defined.");
    }

    /*
     * AbstractDataProcessors
     */
    tmp = this.properties.getProperty(ABSTRACT_DATA_PROCESSORS).trim();
    String[] dps = tmp.split(LIST_SEPARATOR);

    this.dataProcessors = new ArrayList<Class<?>>();
    if (!tmp.equals("")) {
        for (String classString : dps) {
            String[] params = null;
            Class<?>[] paramsClassArray = null;
            classString = classString.trim();

            /*
             * do we have any parameters?
             */
            int pos = classString.indexOf("(");
            if (pos > 0) {
                params = classString.substring(pos + 1, classString.length() - 1).split(",");
                paramsClassArray = new Class[params.length];
                if (params.length > 0) {
                    for (int i = 0; i < params.length; i++) {
                        paramsClassArray[i] = String.class;
                        params[i] = params[i].trim();
                    }
                    classString = classString.substring(0, pos);
                }
            }

            Class<?> clazz;
            try {
                clazz = Class.forName(classString);
            } catch (ClassNotFoundException e) {
                log.error(null, e);
                continue;
            } catch (NoClassDefFoundError e) {
                log.error(null, e);
                continue;
            }

            this.dataProcessors.add(clazz);
        }
    }

    loadExtensions();

    splash.activateProgressBar(
            this.modules.size() + this.dataProcessors.size() + iplugs.size() + oplugs.size());

    /*
     * initialise all modules
     */
    for (IModule module : this.modules) {
        if (module != null) {
            try {
                module.init();
            } catch (Exception e) {
                log.warn(null, e);
            }
        }
        splash.processFinished();
    }

    /*
     * as a last step startup of all output and input plugins as they should not create data before other
     * parts are running.
     */
    for (IOutputPlugin iOutputPlugin : oplugs) {
        if (iOutputPlugin == null)
            continue;
        try {
            registerOutputPlugin(iOutputPlugin);
        } catch (Throwable e) {
            log.warn(e.getMessage(), e);
        }
        splash.processFinished();
    }

    for (IInputPlugin iInputPlugin : iplugs) {
        if (iInputPlugin == null)
            continue;
        try {
            registerInputPlugin(iInputPlugin);
        } catch (Throwable e) {
            log.warn(e.getMessage(), e);
        }
        splash.processFinished();
    }

    /*
     * add all status change listeners
     */
    this.statusChangeListeners.add(this.mainFrame);
    this.outputMessageListeners.add(this.mainFrame);

    /*
     * set the default view
     */
    this.mainFrame.switchToDefaultTab();

    splash.removeSelf();

    this.mainFrame.setVisible(true);
    this.engine.start();

    lifecycleLog.info("Module loading completed.");
}

From source file:org.apache.hadoop.mapred.buffer.net.BufferExchangeSink.java

/** Open the sink for incoming connections. */
public void open() {
    /* Create a new thread for accepting new connections. */
    this.acceptor = new Thread() {
        public void run() {
            try {
                while (server.isOpen()) {
                    LOG.info("in server open");
                    SocketChannel channel = server.accept();
                    channel.configureBlocking(true);
                    /* Note: no buffered input stream due to memory pressure. */
                    DataInputStream istream = new DataInputStream(channel.socket().getInputStream());
                    DataOutputStream ostream = new DataOutputStream(
                            new BufferedOutputStream(channel.socket().getOutputStream()));

                    LOG.info("server is open");
                    if (complete()) {
                        WritableUtils.writeEnum(ostream, Connect.BUFFER_COMPLETE);
                        ostream.close();
                    } else if (handlers.size() > maxConnections) {
                        LOG.info("Connections full. connections = " + handlers.size() + ", max allowed "
                                + maxConnections);
                        WritableUtils.writeEnum(ostream, Connect.CONNECTIONS_FULL);
                        ostream.close();
                    } else {
                        WritableUtils.writeEnum(ostream, Connect.OPEN);
                        ostream.flush();

                        BufferExchange.BufferType type = WritableUtils.readEnum(istream,
                                BufferExchange.BufferType.class);
                        Handler handler = null;
                        if (BufferType.FILE == type) {
                            handler = new FileHandler(collector, istream, ostream);
                        } else if (BufferType.SNAPSHOT == type) {
                            handler = new SnapshotHandler(collector, istream, ostream);
                        } else if (BufferType.STREAM == type) {
                            handler = new StreamHandler(collector, istream, ostream);
                        } else if (BufferType.ITERATE == type) {
                            handler = new IterateHandler(collector, istream, ostream);
                        } else {
                            LOG.error("Unknown buffer type " + type);
                            channel.close();
                            continue;
                        }//w w  w.  j  ava  2 s  .  co m

                        LOG.info("JBufferSink: " + ownerid + " opening connection.");
                        handlers.add(handler);
                        executor.execute(handler);
                    }
                }
                LOG.info("JBufferSink " + ownerid + " buffer response server closed.");
            } catch (IOException e) {
                if (!complete()) {
                    e.printStackTrace();
                }
            }
        }
    };
    acceptor.setDaemon(true);
    acceptor.setPriority(Thread.MAX_PRIORITY);
    acceptor.start();
}

From source file:com.klinker.android.twitter.activities.profile_viewer.ProfilePager.java

public void getUser() {
    Thread getUser = new Thread(new Runnable() {
        @Override/*  w w w  .j  a  va  2 s  .  c o  m*/
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, settings);
                thisUser = twitter.showUser(screenName);
            } catch (Exception e) {
                thisUser = null;
            }

            if (thisUser != null) {
                try {
                    FollowersDataSource.getInstance(context).createUser(thisUser,
                            sharedPrefs.getInt("current_account", 1));

                } catch (Exception e) {
                    // the user already exists. don't know if this is more efficient than querying the db or not.
                }

                final SearchRecentSuggestions suggestions = new SearchRecentSuggestions(context,
                        MySuggestionsProvider.AUTHORITY, MySuggestionsProvider.MODE);
                suggestions.saveRecentQuery("@" + thisUser.getScreenName(), null);
            }

            new GetActionBarInfo().execute();
        }
    });

    getUser.setPriority(Thread.MAX_PRIORITY);
    getUser.start();
}

From source file:cm.aptoide.pt.DownloadQueueService.java

private void downloadFile(final int apkidHash) {

    try {//from   www. ja  v  a 2 s .co m

        new Thread() {
            public void run() {
                this.setPriority(Thread.MAX_PRIORITY);

                if (!keepScreenOn.isHeld()) {
                    keepScreenOn.acquire();
                }
                int threadApkidHash = apkidHash;

                String remotePath = notifications.get(threadApkidHash).get("remotePath");
                String md5hash = notifications.get(threadApkidHash).get("md5hash");

                String localPath = notifications.get(threadApkidHash).get("localPath");
                Log.d("Aptoide-DownloadQueuService",
                        "thread apkidHash: " + threadApkidHash + " localPath: " + localPath);

                Message downloadArguments = new Message();
                try {

                    // If file exists, removes it...
                    File f_chk = new File(localPath);
                    if (f_chk.exists()) {
                        f_chk.delete();
                    }
                    f_chk = null;

                    FileOutputStream saveit = new FileOutputStream(localPath);
                    DefaultHttpClient mHttpClient = new DefaultHttpClient();
                    HttpGet mHttpGet = new HttpGet(remotePath);

                    if (Boolean.parseBoolean(notifications.get(threadApkidHash).get("loginRequired"))) {
                        URL mUrl = new URL(remotePath);
                        mHttpClient.getCredentialsProvider().setCredentials(
                                new AuthScope(mUrl.getHost(), mUrl.getPort()),
                                new UsernamePasswordCredentials(
                                        notifications.get(threadApkidHash).get("username"),
                                        notifications.get(threadApkidHash).get("password")));

                    }

                    HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);

                    if (mHttpResponse == null) {
                        Log.d("Aptoide", "Problem in network... retry...");
                        mHttpResponse = mHttpClient.execute(mHttpGet);
                        if (mHttpResponse == null) {
                            Log.d("Aptoide", "Major network exception... Exiting!");
                            /*msg_al.arg1= 1;
                            download_error_handler.sendMessage(msg_al);*/
                            throw new TimeoutException();
                        }
                    }

                    if (mHttpResponse.getStatusLine().getStatusCode() == 401) {
                        throw new TimeoutException();
                    } else {
                        InputStream getit = mHttpResponse.getEntity().getContent();
                        byte data[] = new byte[8096];
                        int red;
                        red = getit.read(data, 0, 8096);

                        int progressNotificationUpdate = 200;
                        int intermediateProgress = 0;
                        while (red != -1) {
                            if (progressNotificationUpdate == 0) {
                                if (!keepScreenOn.isHeld()) {
                                    keepScreenOn.acquire();
                                }
                                progressNotificationUpdate = 200;
                                Message progressArguments = new Message();
                                progressArguments.arg1 = threadApkidHash;
                                progressArguments.arg2 = intermediateProgress;
                                downloadProgress.sendMessage(progressArguments);
                                intermediateProgress = 0;
                            } else {
                                intermediateProgress += red;
                                progressNotificationUpdate--;
                            }

                            saveit.write(data, 0, red);
                            red = getit.read(data, 0, 8096);
                        }
                        Log.d("Aptoide",
                                "Download done! apkidHash: " + threadApkidHash + " localPath: " + localPath);
                        saveit.flush();
                        saveit.close();
                        getit.close();
                    }

                    if (keepScreenOn.isHeld()) {
                        keepScreenOn.release();
                    }

                    File f = new File(localPath);
                    Md5Handler hash = new Md5Handler();
                    if (md5hash == null || md5hash.equalsIgnoreCase(hash.md5Calc(f))) {
                        downloadArguments.arg1 = 1;
                        downloadArguments.arg2 = threadApkidHash;
                        downloadArguments.obj = localPath;
                        downloadHandler.sendMessage(downloadArguments);
                    } else {
                        Log.d("Aptoide", md5hash + " VS " + hash.md5Calc(f));
                        downloadArguments.arg1 = 0;
                        downloadArguments.arg2 = threadApkidHash;
                        downloadErrorHandler.sendMessage(downloadArguments);
                    }

                } catch (Exception e) {
                    if (keepScreenOn.isHeld()) {
                        keepScreenOn.release();
                    }
                    downloadArguments.arg1 = 1;
                    downloadArguments.arg2 = threadApkidHash;
                    downloadErrorHandler.sendMessage(downloadArguments);
                }
            }
        }.start();

    } catch (Exception e) {
    }
}

From source file:com.obviousengine.android.focus.ZslFocusCamera.java

/**
 * Instantiates a new camera based on Camera 2 API.
 *
 * @param device The underlying Camera 2 device.
 * @param characteristics The device's characteristics.
 * @param pictureSize the size of the final image to be taken.
 */// ww  w  .j a  va2  s.  c  o m
ZslFocusCamera(CameraDevice device, CameraCharacteristics characteristics, Size pictureSize) {
    Timber.v("Creating new ZslFocusCamera");

    this.device = device;
    this.characteristics = characteristics;
    fullSizeAspectRatio = calculateFullSizeAspectRatio(characteristics);

    cameraThread = new HandlerThread("FocusCamera");
    // If this thread stalls, it will delay viewfinder frames.
    cameraThread.setPriority(Thread.MAX_PRIORITY);
    cameraThread.start();
    cameraHandler = new Handler(cameraThread.getLooper());

    cameraListenerThread = new HandlerThread("FocusCamera-Listener");
    cameraListenerThread.start();
    cameraListenerHandler = new Handler(cameraListenerThread.getLooper());

    // TODO: Encoding on multiple cores results in preview jank due to
    // excessive GC.
    int numEncodingCores = Utils.getNumCpuCores();
    imageSaverThreadPool = new ThreadPoolExecutor(numEncodingCores, numEncodingCores, 10, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());

    captureManager = new ImageCaptureManager(MAX_CAPTURE_IMAGES, cameraListenerHandler, imageSaverThreadPool);
    captureManager.setCaptureReadyListener(new ImageCaptureManager.CaptureReadyListener() {
        @Override
        public void onReadyStateChange(boolean capturePossible) {
            readyStateManager.setInput(ReadyStateRequirement.CAPTURE_MANAGER_READY, capturePossible);
        }
    });

    // Listen for changes to auto focus state and dispatch to
    // focusStateListener.
    captureManager.addMetadataChangeListener(CaptureResult.CONTROL_AF_STATE,
            new ImageCaptureManager.MetadataChangeListener() {
                @Override
                public void onImageMetadataChange(Key<?> key, Object oldValue, Object newValue,
                        CaptureResult result) {
                    if (focusStateListener == null) {
                        return;
                    }
                    focusStateListener.onFocusStatusUpdate(
                            AutoFocusHelper.stateFromCamera2State(result.get(CaptureResult.CONTROL_AF_STATE)),
                            result.getFrameNumber());
                }
            });

    // Allocate the image reader to store all images received from the
    // camera.
    if (pictureSize == null) {
        // TODO The default should be selected by the caller, and
        // pictureSize should never be null.
        pictureSize = getDefaultPictureSize();
    }
    captureImageReader = ImageReader.newInstance(pictureSize.getWidth(), pictureSize.getHeight(),
            CAPTURE_IMAGE_FORMAT, MAX_CAPTURE_IMAGES);

    captureImageReader.setOnImageAvailableListener(captureManager, cameraHandler);
    mediaActionSound.load(MediaActionSound.SHUTTER_CLICK);
}

From source file:uk.co.armedpineapple.cth.SDLActivity.java

public static void audioStartThread() {
    mAudioThread = new Thread(new Runnable() {
        public void run() {
            mAudioTrack.play();//from  ww  w.ja va  2s  .c o  m
            nativeRunAudioThread();
        }
    }, "Audio Thread");

    // I'd take REALTIME if I could get it!
    mAudioThread.setPriority(Thread.MAX_PRIORITY);
    mAudioThread.start();
}

From source file:com.daiv.android.twitter.services.TestPullNotificationService.java

@Override
public void onCreate() {
    super.onCreate();

    if (TestPullNotificationService.isRunning) {
        stopSelf();/*from  w  ww  . j  a v  a  2s .co m*/
        return;
    }

    TestPullNotificationService.isRunning = true;

    settings = AppSettings.getInstance(this);

    mCache = App.getInstance(this).getBitmapCache();

    sharedPreferences = getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    showNotification = sharedPreferences.getBoolean("show_pull_notification", true);
    pullUnread = sharedPreferences.getInt("pull_unread", 0);

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Intent stop = new Intent(this, StopPull.class);
    PendingIntent stopPending = PendingIntent.getService(this, 0, stop, 0);

    String text;

    int count = 0;

    if (sharedPreferences.getBoolean("is_logged_in_1", false)) {
        count++;
    }
    if (sharedPreferences.getBoolean("is_logged_in_2", false)) {
        count++;
    }

    boolean multAcc = false;
    if (count == 2) {
        multAcc = true;
    }

    if (settings.liveStreaming && settings.timelineNot) {
        text = getResources().getString(R.string.new_tweets_upper) + ": " + pullUnread;
    } else {
        text = getResources().getString(R.string.listening_for_mentions) + "...";
    }

    mBuilder = new NotificationCompat.Builder(this).setSmallIcon(android.R.color.transparent)
            .setContentTitle(getResources().getString(R.string.Test_pull)
                    + (multAcc ? " - @" + settings.myScreenName : ""))
            .setContentText(text).setOngoing(true)
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_stat_icon));

    if (getApplicationContext().getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.addAction(R.drawable.ic_cancel_dark,
                getApplicationContext().getResources().getString(R.string.stop), stopPending);
    }

    try {
        mBuilder.setWhen(0);
    } catch (Exception e) {
    }

    mBuilder.setContentIntent(pendingIntent);

    // priority flag is only available on api level 16 and above
    if (getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.setPriority(Notification.PRIORITY_MIN);
    }

    mContext = getApplicationContext();

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.daiv.android.twitter.STOP_PUSH");
    registerReceiver(stopPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.daiv.android.twitter.START_PUSH");
    registerReceiver(startPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.daiv.android.twitter.STOP_PUSH_SERVICE");
    registerReceiver(stopService, filter);

    if (settings.liveStreaming && settings.timelineNot) {
        filter = new IntentFilter();
        filter.addAction("com.daiv.android.twitter.UPDATE_NOTIF");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.daiv.android.twitter.NEW_TWEET");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.daiv.android.twitter.CLEAR_PULL_UNREAD");
        registerReceiver(clearPullUnread, filter);
    }

    Thread start = new Thread(new Runnable() {
        @Override
        public void run() {
            // get the ids of everyone you follow
            try {
                Log.v("getting_ids", "started getting ids, mine: " + settings.myId);
                Twitter twitter = Utils.getTwitter(mContext, settings);
                long currCursor = -1;
                IDs idObject;

                ids = new ArrayList<Long>();
                do {
                    idObject = twitter.getFriendsIDs(settings.myId, currCursor);

                    long[] lIds = idObject.getIDs();
                    for (int i = 0; i < lIds.length; i++) {
                        ids.add(lIds[i]);
                    }
                } while ((currCursor = idObject.getNextCursor()) != 0);
                ids.add(settings.myId);

                currCursor = -1;
                blockedIds = new ArrayList<Long>();
                do {
                    idObject = twitter.getBlocksIDs(currCursor);

                    long[] lIds = idObject.getIDs();
                    for (int i = 0; i < lIds.length; i++) {
                        blockedIds.add(lIds[i]);
                    }
                } while ((currCursor = idObject.getNextCursor()) != 0);

                idsLoaded = true;

                if (showNotification)
                    startForeground(FOREGROUND_SERVICE_ID, mBuilder.build());

                mContext.sendBroadcast(new Intent("com.daiv.android.twitter.START_PUSH"));
            } catch (Exception e) {
                e.printStackTrace();
                TestPullNotificationService.isRunning = false;

                pullUnread = 0;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TestPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TestPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                stopSelf();
            } catch (OutOfMemoryError e) {
                TestPullNotificationService.isRunning = false;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TestPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TestPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                pullUnread = 0;

                stopSelf();
            }

        }
    });

    start.setPriority(Thread.MAX_PRIORITY - 1);
    start.start();

}