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:com.curso.listadapter.net.RESTClient.java

/**
 * upload multipart/* ww  w  .j a  v a2s .c  om*/
 * this method receive the file to be uploaded
 * */
@SuppressWarnings("deprecation")
public String uploadMultiPart(Map<String, File> files) throws Exception {
    disableSSLCertificateChecking();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    try {
        URL endpoint = new URL(url);
        conn = (HttpURLConnection) endpoint.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        dos = new DataOutputStream(conn.getOutputStream());
        String post = "";

        //WRITE ALL THE PARAMS
        for (NameValuePair p : params)
            post += writeMultipartParam(p);
        dos.flush();
        //END WRITE ALL THE PARAMS

        //BEGIN THE UPLOAD
        ArrayList<FileInputStream> inputStreams = new ArrayList<FileInputStream>();
        for (Entry<String, File> entry : files.entrySet()) {
            post += lineEnd;
            post += twoHyphens + boundary + lineEnd;
            String NameParamImage = entry.getKey();
            File file = entry.getValue();
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            FileInputStream fileInputStream = new FileInputStream(file);

            post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\""
                    + file.getName() + "\"" + lineEnd;
            String mimetype = getMimeType(file.getName());
            post += "Content-Type: " + mimetype + lineEnd;
            post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd;

            dos.write(post.toString().getBytes("UTF-8"));

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                inputStreams.add(fileInputStream);
            }

            Log.d("Test", post);
            dos.flush();
            post = "";
        }

        //END THE UPLOAD

        dos.writeBytes(lineEnd);

        dos.writeBytes(twoHyphens + boundary + twoHyphens);
        //            for(FileInputStream inputStream: inputStreams){
        //               inputStream.close();
        //            }
        dos.flush();
        dos.close();
        conn.connect();
        Log.d("upload", "finish flush:" + conn.getResponseCode());
    } catch (MalformedURLException ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    try {
        String response_data = "";
        inStream = new DataInputStream(conn.getInputStream());
        String str;
        while ((str = inStream.readLine()) != null) {
            response_data += str;
        }
        inStream.close();
        return response_data;
    } catch (IOException ioex) {
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
    return null;
}

From source file:org.apache.hyracks.control.cc.ClusterControllerService.java

public ClusterControllerService(final CCConfig config, final ICCApplication application) throws Exception {
    this.ccConfig = config;
    this.configManager = ccConfig.getConfigManager();
    if (application == null) {
        throw new IllegalArgumentException("ICCApplication cannot be null");
    }/*from  w  ww.jav a  2  s  .c o m*/
    this.application = application;
    configManager.processConfig();
    File jobLogFolder = new File(ccConfig.getRootDir(), "logs/jobs");
    jobLog = new LogFile(jobLogFolder);

    // WorkQueue is in charge of heartbeat as well as other events.
    workQueue = new WorkQueue("ClusterController", Thread.MAX_PRIORITY);
    this.timer = new Timer(true);
    final ClusterTopology topology = computeClusterTopology(ccConfig);
    ccContext = new ClusterControllerContext(topology);
    sweeper = new DeadNodeSweeper();
    datasetDirectoryService = new DatasetDirectoryService(ccConfig.getResultTTL(),
            ccConfig.getResultSweepThreshold(), preDistributedJobStore);

    deploymentRunMap = new HashMap<>();
    stateDumpRunMap = new HashMap<>();
    threadDumpRunMap = Collections.synchronizedMap(new HashMap<>());

    // Node manager is in charge of cluster membership management.
    nodeManager = new NodeManager(ccConfig, resourceManager);
}

From source file:com.nuvolect.deepdive.lucene.Index.java

public static JSONObject index(final String volumeId, final String searchPath, final boolean forceIndex) {

    if (m_interrupt[0]) {

        LogUtil.log(LogUtil.LogType.INDEX, "Index canceled post interrupt");

        m_interrupt[0] = false;/*w ww  .  ja v  a2 s . c  o m*/
        return responseInterruptIndexing();
    }

    OmniFile cacheDir = IndexUtil.getCacheDir(volumeId, searchPath);
    boolean cacheDirCreated = false;
    try {
        cacheDirCreated = OmniUtil.forceMkdir(cacheDir);
    } catch (IOException e) {
        return responseFolderCreateError(searchPath);
    }

    final String luceneDirPath = cacheDir.getAbsolutePath();

    boolean cacheDirExists = !cacheDirCreated;
    boolean indexingOngoing = m_indexThread != null && m_indexThread.isAlive();
    boolean indexingRequired = !cacheDirExists || forceIndex;

    synchronized (m_lock) {

        if (indexingOngoing) {

            if (m_fileTreeActive)
                m_index_state = INDEX_STATE.filetree;
            else
                m_index_state = INDEX_STATE.indexing;
        } else {
            if (indexingRequired)
                m_index_state = INDEX_STATE.indexing;
            else
                m_index_state = INDEX_STATE.complete;
        }
    }

    if (indexingRequired || indexingOngoing) {

        if (indexingOngoing) {

            // Nothing to do, let the background process run. Monitor m_indexedDocs for progress.
        } else {

            synchronized (m_lock) {
                m_index_state = INDEX_STATE.filetree;
                m_totalDocs[0] = 0;
                m_indexedDocs[0] = 0;
                m_error[0] = "";
            }
            m_threadGroup = new ThreadGroup(INDEX_THREAD_GROUP);
            m_indexThread = new Thread(m_threadGroup, new Runnable() {
                @Override
                public void run() {

                    //                        Analyzer analyzer = new org.apache.lucene.analysis.core.WhitespaceAnalyzer();
                    //                        Analyzer analyzer = new org.apache.lucene.analysis.core.KeywordAnalyzer();
                    //                        Analyzer analyzer = new org.apache.lucene.analysis.standard.StandardAnalyzer();
                    Analyzer analyzer = new org.apache.lucene.analysis.core.SimpleAnalyzer();
                    IndexWriterConfig config = new IndexWriterConfig(analyzer);
                    IndexWriter iwriter = null;

                    try {
                        Directory m_directory = FSDirectory.open(Paths.get(luceneDirPath));
                        iwriter = new IndexWriter(m_directory, config);
                        iwriter.deleteAll();
                        iwriter.commit();
                    } catch (IOException e) {
                        LogUtil.logException(LogUtil.LogType.INDEX, e);
                        m_error[0] = "IndexWriter constructor exception";
                    }

                    synchronized (m_lock) {
                        m_fileTreeActive = true;
                        m_index_state = INDEX_STATE.filetree;
                    }
                    Collection<OmniFile> files = IndexUtil.getFilePaths(volumeId, searchPath);

                    synchronized (m_lock) {
                        m_index_state = INDEX_STATE.indexing;
                        m_fileTreeActive = false;
                        m_totalDocs[0] = files.size();
                        m_indexedDocs[0] = 0;
                    }

                    try {

                        for (OmniFile file : files) {

                            if (m_interrupt[0]) {
                                LogUtil.log(LogUtil.LogType.INDEX, "Iterator loop canceled");
                                break;
                            }

                            String path = file.getPath();

                            //                                LogUtil.log(LogUtil.LogType.INDEX, "indexing: " + path);// this is a bit excessive
                            iwriter.addDocument(makeDoc(volumeId, path));
                            synchronized (m_lock) {
                                ++m_indexedDocs[0];
                            }
                        }

                        iwriter.commit();
                        iwriter.close();
                        synchronized (m_lock) {
                            m_index_state = m_interrupt[0] ? INDEX_STATE.interrupted : INDEX_STATE.complete;
                            m_totalDocs[0] = m_indexedDocs[0];
                        }

                    } catch (Exception e) {
                        LogUtil.logException(LogUtil.LogType.INDEX, e);
                        m_error[0] = "IndexWriter addDocument exception";
                    }
                }
            }, INDEX_THREAD, STACK_SIZE);

            m_indexThread.setPriority(Thread.MAX_PRIORITY);
            m_indexThread.start();
        }
    } else {

        // Indexing is complete
        // Get number of documents indexed
        try {
            Directory directory = FSDirectory.open(Paths.get(luceneDirPath));
            DirectoryReader ireader = DirectoryReader.open(directory);
            synchronized (m_lock) {
                m_indexedDocs[0] = ireader.numDocs();
                m_totalDocs[0] = m_indexedDocs[0];
                m_index_state = INDEX_STATE.complete;
            }
            ireader.close();
            directory.close();
        } catch (IOException e) {
            LogUtil.logException(LogUtil.LogType.INDEX, e);
        }
    }

    JSONObject result = new JSONObject();
    try {
        synchronized (m_lock) {
            result.put("index_state", m_index_state.toString());
            result.put("error", m_error[0]);
            result.put("indexed_docs", m_indexedDocs[0]);
            result.put("total_docs", m_totalDocs[0]);
            //                result.put("full_path", cacheDir.getAbsolutePath());
            result.put("search_path", searchPath);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return result;
}

From source file:it.lilik.capturemjpeg.CaptureMJPEG.java

/**
 * Creates a <code>CaptureMJPEG</code> with HTTP Auth credential
 * // w w w . j  a v  a 2 s  .c o m
 * @param parent the <code>ImageWindow</code> which uses this object
 * @param url the MJPEG stream URI
 * @param username HTTP AUTH username
 * @param password HTTP AUTH password
 */
public CaptureMJPEG(VideoPanel parent, String url, String username, String password) {
    this.lastImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    //this.lastImage.init(parent.width, parent.height, PImage.RGB);
    this.method = new GetMethod(url);
    this.shouldStop = false;
    this.changeImageSize = false;
    buffer = new CircularBuffer();
    // create a singular HttpClient object
    this.client = new HttpClient();

    // establish a connection within 5 seconds
    this.client.getHttpConnectionManager().getParams().setConnectionTimeout(HTTP_TIMEOUT);

    if (username != null && password != null) {
        this.setCredential(username, password);
    }
    setURL(url);
    //set the ThreadName useful for debug
    setName("CaptureMJPEG");
    setPriority(Thread.MAX_PRIORITY);

    this.parent = parent;

    //System.out.println("Capture initialized");

    //parent.registerDispose(this);       
    //register callback
    try {
        captureEventMethod = parent.getClass().getMethod("captureMJPEGEvent", new Class[] { Image.class });
    } catch (Exception e) {
        System.out.println("Cannot set callback " + e.getMessage());
    }
}

From source file:ffx.numerics.fft.Complex3DCuda.java

/**
 * <p>//  w ww . j ava2  s  .c  o m
 * main</p>
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws java.lang.Exception if any.
 */
public static void main(String[] args) throws Exception {
    int dimNotFinal = 64;
    int reps = 10;
    if (args != null) {
        try {
            dimNotFinal = Integer.parseInt(args[0]);
            if (dimNotFinal < 1) {
                dimNotFinal = 64;
            }
            reps = Integer.parseInt(args[1]);
            if (reps < 1) {
                reps = 10;
            }
        } catch (Exception e) {
        }
    }
    final int dim = dimNotFinal;

    System.out.println(String.format(
            " Initializing a %d cubed grid.\n" + " The best timing out of %d repititions will be used.", dim,
            reps));

    final int dimCubed = dim * dim * dim;

    /**
     * Create an array to save the initial input and result.
     */
    double orig[] = new double[dimCubed];
    double answer[] = new double[dimCubed];
    double data[] = new double[dimCubed * 2];
    double recip[] = new double[dimCubed];

    Random random = new Random(1);
    int index = 0;
    for (int k = 0; k < dim; k++) {
        for (int j = 0; j < dim; j++) {
            for (int i = 0; i < dim; i++) {
                orig[index] = random.nextDouble();
                //recip[index] = orig[index];
                recip[index] = 1.0;
                index++;
            }
        }
    }

    Complex3D complex3D = new Complex3D(dim, dim, dim);
    Complex3DParallel complex3DParallel = new Complex3DParallel(dim, dim, dim, new ParallelTeam(),
            IntegerSchedule.fixed());
    complex3DParallel.setRecip(recip);

    Complex3DCuda complex3DCUDA = new Complex3DCuda(dim, dim, dim);
    Thread cudaThread = new Thread(complex3DCUDA);
    cudaThread.setPriority(Thread.MAX_PRIORITY);
    cudaThread.start();
    complex3DCUDA.setRecip(recip);

    double toSeconds = 0.000000001;
    long parTime = Long.MAX_VALUE;
    long seqTime = Long.MAX_VALUE;
    long clTime = Long.MAX_VALUE;

    complex3D.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        //complex3D.convolution(data);
        complex3D.fft(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Sequential: %8.3f", i + 1, toSeconds * time));
        if (time < seqTime) {
            seqTime = time;
        }
    }

    for (int j = 0; j < dimCubed; j++) {
        answer[j] = data[j * 2];
    }

    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        //complex3DParallel.convolution(data);
        complex3DParallel.fft(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Parallel:   %8.3f", i + 1, toSeconds * time));
        if (time < parTime) {
            parTime = time;
        }
    }

    double maxError = Double.MIN_VALUE;
    double rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs(answer[i] - data[2 * i]);
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" Parallel RMSE:   %12.10f, Max: %12.10f", rmse, maxError));

    DoubleBuffer cudaBuffer = complex3DCUDA.getDoubleBuffer();
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            // data[j * 2] = orig[j];
            // data[j * 2 + 1] = 0.0;
            cudaBuffer.put(j * 2, orig[j]);
            cudaBuffer.put(j * 2 + 1, 0.0);
        }
        long time = System.nanoTime();
        //complex3DCUDA.convolution(data);
        complex3DCUDA.fft(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d CUDA:     %8.3f", i + 1, toSeconds * time));
        if (time < clTime) {
            clTime = time;
        }
    }

    maxError = Double.MIN_VALUE;
    double avg = 0.0;
    rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs(answer[i] - cudaBuffer.get(2 * i));
        // double error = Math.abs(answer[i] / dimCubed -  data[2 * i]);
        avg += error;
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    avg /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" CUDA RMSE:   %12.10f, Max: %12.10f, Avg: %12.10f", rmse, maxError, avg));

    complex3DCUDA.free();
    complex3DCUDA = null;

    System.out.println(String.format(" Best Sequential Time:  %8.3f", toSeconds * seqTime));
    System.out.println(String.format(" Best Parallel Time:    %8.3f", toSeconds * parTime));
    System.out.println(String.format(" Best CUDA Time:        %8.3f", toSeconds * clTime));
    System.out.println(String.format(" Parallel Speedup: %15.5f", (double) seqTime / parTime));
    System.out.println(String.format(" CUDA Speedup:     %15.5f", (double) seqTime / clTime));
}

From source file:com.rp.podemu.PodEmuService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    try {//  w  w w  . ja  va 2 s . c o m
        if (bufferThread != null || bgThread != null) {
            PodEmuLog.debug("Service already running...");
            return Service.START_STICKY;
        }

        reloadBaudRate();

        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notification_icon)
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.podemu_icon))
                .setContentTitle("PodEmu").setContentText("iPod emulation is running")
                .setContentIntent(pendingIntent).build();
        startForeground(1, notification);

        /*
         * Buffer thread is used only to read from serial interface and put bytes into internal buffer.
         * It is important for this thread to have the highest priority, because internal buffer
         * of serial devices usually has only 255 bytes and not reading data fast enough can cause
         * some bytes to be lost.
         */
        if (bufferThread == null) {
            bufferThread = new Thread(new Runnable() {
                public void run() {
                    try {
                        serialInterface = serialInterfaceBuilder.getSerialInterface();
                        int numBytesRead;

                        // some devices have problem reading less then internal chip buffer
                        // size (due to android bug 28023), therefore we need to set
                        // expected buffer size equal to internal buffer size of the device
                        byte buffer[] = new byte[serialInterface.getReadBufferSize()];
                        PodEmuLog.debug("Buffer thread started.");

                        serialInterface.setBaudRate(Integer.parseInt(baudRate));

                        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
                        //android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);

                        numBytesRead = 0;
                        while (true) {
                            try {
                                if (numBytesRead < 0 || !serialInterface.isConnected()) {
                                    PodEmuLog.error("Read attempt nr " + failedReadCount
                                            + " when interface is disconnected");
                                    Thread.sleep(100);
                                    failedReadCount++;
                                    if (failedReadCount > 50) // 5 seconds
                                    {
                                        PodEmuLog.error(
                                                "Something wrong happen. Reading from serial interface constantly failing. Terminating service.");
                                        stopSelf();
                                    }
                                }

                                // Reading incoming data
                                while ((numBytesRead = serialInterface.read(buffer)) > 0) {
                                    //PodEmuLog.debug("RECEIVED BYTES: " + numBytesRead);
                                    for (int j = 0; j < numBytesRead; j++) {
                                        inputBuffer.add(buffer[j]);
                                    }
                                }
                                if (numBytesRead == 0) {
                                    Thread.sleep(10);
                                    failedReadCount = 0;
                                }

                            } catch (Exception e) {
                                if (!(e instanceof InterruptedException)) {
                                    // sth wrong happen, just log and throw it up
                                    PodEmuLog.printStackTrace(e);
                                }
                                throw e;
                            }
                        }

                    } catch (InterruptedException e) {
                        PodEmuLog.debug("Buffer thread interrupted!");
                    }
                }
            });
            bufferThread.start();
        }

        /*
         * This is polling thread that will only post message 0x0027 to the serial interface if
         * polling mode is enabled.
         */
        if (pollingThread == null) {
            pollingThread = new Thread(new Runnable() {
                public void run() {
                    try {
                        boolean stopCommandSent = false;
                        MediaPlayback mediaPlayback = MediaPlayback.getInstance();

                        while (true) {

                            if (oapMessenger.getPollingMode()) {
                                if (mediaPlayback.getTrackStatusChanged()) {
                                    mediaPlayback.setTrackStatusChanged(false);
                                    oapMessenger.oap_04_write_polling_track_status_changed(
                                            mediaPlayback.getCurrentPlaylist().getCurrentTrackPos());
                                }

                                if (!mediaPlayback.isPlaying() && !stopCommandSent) {
                                    oapMessenger.oap_04_write_polling_playback_stopped();
                                    stopCommandSent = true;
                                }
                                if (mediaPlayback.isPlaying())
                                    stopCommandSent = false;

                                oapMessenger.oap_04_write_polling_elapsed_time();
                            }
                            Thread.sleep(500);
                        }

                    } catch (InterruptedException e) {
                        PodEmuLog.debug("Polling thread interrupted!");
                    }
                }
            });
            pollingThread.start();
        }

        /*
         * this is main thread that reads data from serial interface internal buffer
         * and processes it byte by byte
         */
        if (bgThread == null) {
            bgThread = new Thread(new Runnable() {
                public void run() {
                    try {
                        int numBytesRead = 0;
                        byte buffer[] = new byte[1];
                        PodEmuLog.debug("Background thread started.");

                        while (true) {
                            //serialInterface.write("Service is running...".getBytes(), 21);

                            numBytesRead = 0;
                            // Reading incoming data
                            while (inputBuffer.remove(buffer) > 0) {
                                oapMessenger.oap_receive_byte(buffer[0]);
                                numBytesRead++;
                            }

                            // sending updates
                            while (podEmuMessageVector.size() > 0) {
                                PodEmuMessage podEmuMessage = podEmuMessageVector.get(0);
                                MediaPlayback.getInstance().updateCurrentlyPlayingTrack(podEmuMessage);
                                podEmuMessageVector.remove(0);
                            }
                            oapMessenger.flush();

                            if (numBytesRead == 0) {
                                Thread.sleep(10);
                            }
                        }
                    } catch (InterruptedException e) {
                        PodEmuLog.debug("Background processing thread interrupted!");
                    } catch (Exception e) {
                        PodEmuLog.printStackTrace(e);
                        throw e;
                    }
                }

            });
            bgThread.start();
        }

        PodEmuLog.debug("Service started");
        return Service.START_STICKY;
    } catch (Exception e) {
        PodEmuLog.printStackTrace(e);
        throw e;
    }
}

From source file:net.pms.util.BasicThreadFactory.java

/**
 * Creates a new {@link BasicThreadFactory} using the given arguments.
 * <p>/*from   www  .  j a  va2 s.  c om*/
 * The {@link Thread} names generated by the new {@link BasicThreadFactory}
 * is created by calling {@link String#format} with {@code namePattern} as
 * the "format" and pool- and thread number as arguments. The formatting
 * rules are those of {@link java.util.Formatter}.
 * <p>
 * No more than two variables of type {@code %d} or {@code %s} is allowed in
 * {@code namePattern}, and they will be substituted as follows:
 * <ul>
 * <li>No variables: All {@link Thread} names generated by this
 * {@link ThreadFactory} will be equal to {@code namePattern}.</li>
 * <li>One variable: Only thread number will be used, pool number isn't
 * used.</li>
 * <li>Two variables: Pool number will be used for the first variable in
 * {@code namePattern}, thread number for the second.
 * </ul>
 *
 * @param namePattern The {@link java.util.Formatter} formatted
 *            {@link String} from which to generate {@link Thread} names.
 * @param threadPriority The {@link Thread} priority.
 * @param group The {@link ThreadGroup}.
 */
public BasicThreadFactory(String namePattern, int threadPriority, ThreadGroup group) {
    if (isBlank(namePattern)) {
        throw new IllegalArgumentException("namePattern cannot be blank");
    }
    if (group == null) {
        SecurityManager securityManager = System.getSecurityManager();
        group = (securityManager != null) ? securityManager.getThreadGroup()
                : Thread.currentThread().getThreadGroup();
    }
    this.group = group;
    this.threadPriority = Math.min(Thread.MAX_PRIORITY, Math.max(Thread.MIN_PRIORITY, threadPriority));
    int pctSes = 0;
    int pctDs = 0;
    int i = 0;
    while (true) {
        i = namePattern.indexOf("%s", i);
        if (i >= 0) {
            pctSes++;
            i++;
        } else {
            break;
        }
    }
    while (true) {
        i = namePattern.indexOf("%d", i);
        if (i >= 0) {
            pctDs++;
            i++;
        } else {
            break;
        }
    }
    if (pctSes + pctDs > 2) {
        throw new IllegalArgumentException("namePattern can't have more than 2 variables");
    }
    this.numVariables = pctSes + pctDs;
    this.namePattern = namePattern;
    if (numVariables == 2) {
        this.instancePoolNumber = POOL_NUMBER.getAndIncrement();
    } else {
        this.instancePoolNumber = 0;
    }
}

From source file:morphy.service.SocketConnectionService.java

private SocketConnectionService() {
    MorphyPreferences morphyPreferences = Morphy.getInstance().getMorphyPreferences();
    try {//from  www.jav a  2  s  .  c  o m
        maxCommunicationSizeBytes = morphyPreferences
                .getInt(PreferenceKeys.SocketConnectionServiceMaxCommunicationBytes);
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);

        /*Object obj = PreferenceService.getInstance().getProperty(PreferenceKeys.SocketConnectionServicePorts.toString());
        System.out.println(obj.getClass());
        if (obj instanceof java.util.ArrayList) {
           //System.out.println((java.util.ArrayList<String>)obj);
           String[] arr = ((java.util.ArrayList<String>)obj).toArray(new String[0]);
           System.out.println(java.util.Arrays.toString(arr));
           //serverSocketChannel.socket().
           for(int i=0;i<arr.length;i++) {
              serverSocketChannel.socket().bind( 
             new java.net.InetSocketAddress( Integer.parseInt(arr[i]) ));
              if (LOG.isInfoEnabled()) {
          LOG.info("Listening on port " + arr[i]);
              }
           }
        } else {
           if (LOG.isInfoEnabled()) {
              serverSocketChannel.socket().bind( new java.net.InetSocketAddress( 5000 ));
              LOG.info("LOAD CONFIG FAILED - Listening on port 5000");
           }
        }*/

        serverSocketChannel.socket().bind(new java.net.InetSocketAddress(
                morphyPreferences.getInt(PreferenceKeys.SocketConnectionServicePorts.toString())));
        serverSocketSelector = Selector.open();
        serverSocketChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);

        selectionThread = new Thread(selectSocketRunnable);
        selectionThread.setPriority(Thread.MAX_PRIORITY);
        selectionThread.start();

        LOG.info("Initialized Socket Connection Service host:" + serverSocketChannel.socket().getInetAddress()
                + " " + serverSocketChannel.socket().getLocalPort());

        this.timesealCoder = new TimesealCoder();
    } catch (Throwable t) {
        if (LOG.isErrorEnabled())
            LOG.error("Error initializing SocketConnectionService", t);
    }
}

From source file:org.wso2.carbon.clustering.hazelcast.HazelcastGroupManagementAgent.java

private void connectMember(Member member) {
    if (!member.getDomain().equals(domain) || !subDomain.equals(member.getProperties().get("subDomain"))) {
        return;//from  w  ww .  jav  a  2s . c om
    }
    if (!connectedMembers.contains(member)) {
        Thread th = new Thread(new MemberAdder(member));
        th.setPriority(Thread.MAX_PRIORITY);
        th.start();
    }
}

From source file:org.jboss.dashboard.profiler.Profiler.java

public void turnOn() {
    if (!running) {
        running = true;//w ww  . ja v  a 2  s  .  c  om
        profilerThread = new Thread(this, "Profiler thread");
        profilerThread.setPriority(Thread.MAX_PRIORITY);
        profilerThread.setDaemon(true);
        profilerThread.start();
    }
}