Example usage for java.lang Thread MIN_PRIORITY

List of usage examples for java.lang Thread MIN_PRIORITY

Introduction

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

Prototype

int MIN_PRIORITY

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

Click Source Link

Document

The minimum priority that a thread can have.

Usage

From source file:im.vector.util.VectorRoomMediasSender.java

/**
 * Offer to resize the image before sending it.
 * @param aThumbnailURL the thumbnail url
 * @param anImageUrl the image url./*from w  w  w. ja v  a2  s .  c  o m*/
 * @param anImageFilename the image filename
 * @param anImageMimeType the image mimetype
 * @param aListener the listener
 */
private void sendImageMessage(final String aThumbnailURL, final String anImageUrl, final String anImageFilename,
        final String anImageMimeType, final OnImageUploadListener aListener) {
    // sanity check
    if ((null == anImageUrl) || (null == aListener)) {
        return;
    }

    boolean isManaged = false;

    // check if the media could be resized
    if ((null != aThumbnailURL) && (CommonActivityUtils.MIME_TYPE_JPEG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_JPG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_IMAGE_ALL.equals(anImageMimeType))) {
        System.gc();
        FileInputStream imageStream;

        try {
            Uri uri = Uri.parse(anImageUrl);
            final String filename = uri.getPath();

            final int rotationAngle = ImageUtils.getRotationAngleForBitmap(mVectorRoomActivity, uri);

            imageStream = new FileInputStream(new File(filename));

            int fileSize = imageStream.available();

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            options.outWidth = -1;
            options.outHeight = -1;

            // retrieve the image size
            try {
                BitmapFactory.decodeStream(imageStream, null, options);
            } catch (OutOfMemoryError e) {
                Log.e(LOG_TAG, "sendImageMessage out of memory error : " + e.getMessage());
            }

            final ImageCompressionSizes imageSizes = computeImageSizes(options.outWidth, options.outHeight);

            imageStream.close();

            // the user already selects a compression
            if (null != mImageCompressionDescription) {
                isManaged = true;

                final ImageSize expectedSize = imageSizes.getImageSize(mVectorRoomActivity,
                        mImageCompressionDescription);
                final String fImageUrl = resizeImage(anImageUrl, filename, imageSizes.mFullImageSize,
                        expectedSize, rotationAngle);

                mVectorRoomActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mVectorMessageListFragment.uploadImageContent(aThumbnailURL, fImageUrl, anImageFilename,
                                anImageMimeType);
                        aListener.onDone();
                    }
                });
            }
            // can be rescaled ?
            else if (null != imageSizes.mSmallImageSize) {
                isManaged = true;

                FragmentManager fm = mVectorRoomActivity.getSupportFragmentManager();
                ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm
                        .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG);

                if (fragment != null) {
                    fragment.dismissAllowingStateLoss();
                }

                String[] stringsArray = getImagesCompressionTextsList(mVectorRoomActivity, imageSizes,
                        fileSize);

                final AlertDialog.Builder alert = new AlertDialog.Builder(mVectorRoomActivity);
                alert.setTitle(mVectorRoomActivity.getString(im.vector.R.string.compression_options));
                alert.setSingleChoiceItems(stringsArray, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final int fPos = which;

                        mImageSizesListDialog.dismiss();

                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mVectorRoomActivity.setProgressVisibility(View.VISIBLE);

                                Thread thread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ImageSize expectedSize = null;

                                        // full size
                                        if (0 != fPos) {
                                            expectedSize = imageSizes.getImageSizesList().get(fPos);
                                        }

                                        // stored the compression selected by the user
                                        mImageCompressionDescription = imageSizes
                                                .getImageSizesDescription(mVectorRoomActivity).get(fPos);

                                        final String fImageUrl = resizeImage(anImageUrl, filename,
                                                imageSizes.mFullImageSize, expectedSize, rotationAngle);

                                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                mVectorMessageListFragment.uploadImageContent(aThumbnailURL,
                                                        fImageUrl, anImageFilename, anImageMimeType);
                                                aListener.onDone();
                                            }
                                        });
                                    }
                                });

                                thread.setPriority(Thread.MIN_PRIORITY);
                                thread.start();
                            }
                        });
                    }
                });

                mImageSizesListDialog = alert.show();
                mImageSizesListDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        mImageSizesListDialog = null;
                        if (null != aListener) {
                            aListener.onCancel();
                        }
                    }
                });
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "sendImageMessage failed " + e.getMessage());
        }
    }

    // cannot resize, let assumes that it has been done
    if (!isManaged) {
        mVectorRoomActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mVectorMessageListFragment.uploadImageContent(aThumbnailURL, anImageUrl, anImageFilename,
                        anImageMimeType);
                if (null != aListener) {
                    aListener.onDone();
                }
            }
        });
    }
}

From source file:im.neon.util.VectorRoomMediasSender.java

/**
 * Offer to resize the image before sending it.
 * @param aThumbnailURL the thumbnail url
 * @param anImageUrl the image url./*from   w  w w . jav  a  2 s .c  o m*/
 * @param anImageFilename the image filename
 * @param anImageMimeType the image mimetype
 * @param aListener the listener
 */
private void sendImageMessage(final String aThumbnailURL, final String anImageUrl, final String anImageFilename,
        final String anImageMimeType, final OnImageUploadListener aListener) {
    // sanity check
    if ((null == anImageUrl) || (null == aListener)) {
        return;
    }

    boolean isManaged = false;

    // check if the media could be resized
    if ((null != aThumbnailURL) && (CommonActivityUtils.MIME_TYPE_JPEG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_JPG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_IMAGE_ALL.equals(anImageMimeType))) {
        System.gc();
        FileInputStream imageStream;

        try {
            Uri uri = Uri.parse(anImageUrl);
            final String filename = uri.getPath();

            final int rotationAngle = ImageUtils.getRotationAngleForBitmap(mVectorRoomActivity, uri);

            imageStream = new FileInputStream(new File(filename));

            int fileSize = imageStream.available();

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            options.outWidth = -1;
            options.outHeight = -1;

            // retrieve the image size
            try {
                BitmapFactory.decodeStream(imageStream, null, options);
            } catch (OutOfMemoryError e) {
                Log.e(LOG_TAG, "sendImageMessage out of memory error : " + e.getMessage());
            }

            final ImageCompressionSizes imageSizes = computeImageSizes(options.outWidth, options.outHeight);

            imageStream.close();

            // the user already selects a compression
            if (null != mImageCompressionDescription) {
                isManaged = true;

                final ImageSize expectedSize = imageSizes.getImageSize(mVectorRoomActivity,
                        mImageCompressionDescription);
                final String fImageUrl = resizeImage(anImageUrl, filename, imageSizes.mFullImageSize,
                        expectedSize, rotationAngle);

                mVectorRoomActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mVectorMessageListFragment.uploadImageContent(null, null, aThumbnailURL, fImageUrl,
                                anImageFilename, anImageMimeType);
                        aListener.onDone();
                    }
                });
            }
            // can be rescaled ?
            else if (null != imageSizes.mSmallImageSize) {
                isManaged = true;

                FragmentManager fm = mVectorRoomActivity.getSupportFragmentManager();
                ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm
                        .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG);

                if (fragment != null) {
                    fragment.dismissAllowingStateLoss();
                }

                String[] stringsArray = getImagesCompressionTextsList(mVectorRoomActivity, imageSizes,
                        fileSize);

                final AlertDialog.Builder alert = new AlertDialog.Builder(mVectorRoomActivity);
                alert.setTitle(mVectorRoomActivity.getString(im.neon.R.string.compression_options));
                alert.setSingleChoiceItems(stringsArray, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final int fPos = which;

                        mImageSizesListDialog.dismiss();

                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mVectorRoomActivity.setProgressVisibility(View.VISIBLE);

                                Thread thread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ImageSize expectedSize = null;

                                        // full size
                                        if (0 != fPos) {
                                            expectedSize = imageSizes.getImageSizesList().get(fPos);
                                        }

                                        // stored the compression selected by the user
                                        mImageCompressionDescription = imageSizes
                                                .getImageSizesDescription(mVectorRoomActivity).get(fPos);

                                        final String fImageUrl = resizeImage(anImageUrl, filename,
                                                imageSizes.mFullImageSize, expectedSize, rotationAngle);

                                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                mVectorMessageListFragment.uploadImageContent(null, null,
                                                        aThumbnailURL, fImageUrl, anImageFilename,
                                                        anImageMimeType);
                                                aListener.onDone();
                                            }
                                        });
                                    }
                                });

                                thread.setPriority(Thread.MIN_PRIORITY);
                                thread.start();
                            }
                        });
                    }
                });

                mImageSizesListDialog = alert.show();
                mImageSizesListDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        mImageSizesListDialog = null;
                        if (null != aListener) {
                            aListener.onCancel();
                        }
                    }
                });
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "sendImageMessage failed " + e.getMessage());
        }
    }

    // cannot resize, let assumes that it has been done
    if (!isManaged) {
        mVectorRoomActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mVectorMessageListFragment.uploadImageContent(null, null, aThumbnailURL, anImageUrl,
                        anImageFilename, anImageMimeType);
                if (null != aListener) {
                    aListener.onDone();
                }
            }
        });
    }
}

From source file:ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository.java

/**
 * Creates the previews for this resource in all languages and for all known
 * image styles. The implementation ensures that there is only one preview
 * renderer running per resource.//from   w w w  . j a  v  a 2  s. c o  m
 * 
 * @param resource
 *          the resource
 * @param languages
 *          the languages to build the previews for
 */
protected void createPreviews(final Resource<?> resource, Language... languages) {

    ResourceURI uri = resource.getURI();

    // Compile the full list of image styles
    if (imageStyleTracker == null) {
        logger.info("Skipping preview generation for {}: image styles are unavailable", uri);
        return;
    }

    final List<ImageStyle> previewStyles = new ArrayList<ImageStyle>();

    // Add the global image styles that have the preview flag turned on
    for (ImageStyle s : imageStyleTracker.getImageStyles()) {
        if (s.isPreview()) {
            previewStyles.add(s);
            logger.debug("Preview images will be generated for {}", s);
        } else {
            logger.debug("Preview image generation will be skipped for {}", s);
        }
    }

    // Add the site's preview image styles as well as
    for (Module m : getSite().getModules()) {
        for (ImageStyle s : m.getImageStyles()) {
            if (s.isPreview()) {
                previewStyles.add(s);
                logger.debug("Preview images will be generated for {}", s);
            } else {
                logger.debug("Preview image generation will be skipped for {}", s);
            }
        }
    }

    // If no language has been specified, we create the preview for all
    // languages
    if (languages == null || languages.length == 0) {
        languages = uri.getSite().getLanguages();
    }

    // Create the previews
    PreviewOperation previewOp = null;
    synchronized (currentPreviewOperations) {

        // is there an existing operation for this resource? If so, simply update
        // it and be done.
        previewOp = previews.get(uri);
        if (previewOp != null) {
            PreviewGeneratorWorker worker = previewOp.getWorker();
            if (worker != null) {
                logger.info("Canceling current preview generation for {} in favor of more recent data", uri);
                worker.cancel();
            }
        }

        // Otherwise, a new preview generator needs to be started.
        previewOp = new PreviewOperation(resource, Arrays.asList(languages), previewStyles,
                ImageStyleUtils.DEFAULT_PREVIEW_FORMAT);

        // Make sure nobody is working on the same resource at the moment
        if (currentPreviewOperations.contains(previewOp)) {
            logger.debug("Queing concurring creation of preview for {}", uri);
            previews.put(uri, previewOp);
            previewOperations.add(previewOp);
            return;
        }

        // If there is enough being worked on already, there is nothing we can do
        // right now, the work will be picked up later on
        if (currentPreviewOperations.size() >= maxPreviewOperations) {
            logger.debug("Queing creation of preview for {}", uri);
            previews.put(uri, previewOp);
            previewOperations.add(previewOp);
            logger.debug("Preview generation queue now contains {} resources", previews.size());
            return;
        }

        // It seems like it is safe to start the preview generation
        currentPreviewOperations.add(previewOp);
        PreviewGeneratorWorker previewWorker = new PreviewGeneratorWorker(this, previewOp.getResource(),
                environment, previewOp.getLanguages(), previewOp.getStyles(), previewOp.getFormat());
        previewOp.setWorker(previewWorker);
        Thread t = new Thread(previewWorker);
        t.setPriority(Thread.MIN_PRIORITY);
        t.setDaemon(true);

        logger.debug("Creating preview of {}", uri);
        t.start();
    }
}

From source file:weka.server.WekaServer.java

/**
 * Send status info for the supplied task back to the master server
 * //www  .  j  a v  a2s  .c  o  m
 * @param entry the task entry for the task in question
 * @param taskStatus the status to send
 */
protected void sendTaskStatusInfoToMaster(final WekaTaskEntry entry, final int taskStatus) {

    Thread t = new Thread() {
        @Override
        public void run() {
            PostMethod post = null;
            InputStream is = null;
            try {
                String url = "http://" + m_master;
                url = url.replace(" ", "%20");
                url += SetTaskStatusServlet.CONTEXT_PATH;
                url += "/?name=" + entry.toString();
                url += "&status=" + taskStatus;

                post = new PostMethod(url);
                post.setDoAuthentication(true);
                post.addRequestHeader(new Header("Content-Type", "text/plain"));

                // Get HTTP client
                HttpClient client = ConnectionManager.getSingleton().createHttpClient();
                ConnectionManager.addCredentials(client, m_username, m_password);

                // Execute request
                int result = client.executeMethod(post);
                // System.out.println("[WekaServer] SendTaskStatus: Response from master server : "
                // + result);
                if (result == 401) {
                    System.err.println("[WekaServer] Unable to send task status back to master"
                            + " - authentication required.\n");
                } else {

                    // the response
                    is = post.getResponseBodyAsStream();
                    ObjectInputStream ois = new ObjectInputStream(is);
                    Object response = ois.readObject();
                    if (response.toString().startsWith(WekaServlet.RESPONSE_ERROR)) {
                        System.err.println("[WekaServer] A problem occurred while "
                                + "trying to send task status back to master server : \n" + "\t"
                                + response.toString());
                    } else {
                        // System.out.println("[WekaServer] " + response.toString());
                    }
                }
            } catch (Exception ex) {
                System.err.println("[WekaServer] A problem occurred while "
                        + "trying to send task status back to master server : \n" + ex.getMessage());
                ex.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (post != null) {
                    post.releaseConnection();
                }
            }
        }
    };

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

From source file:ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository.java

/**
 * Callback for the preview renderer to indicate a finished rendering
 * operation.//www . java 2 s.  com
 * 
 * @param resource
 *          the resource
 */
void previewCreated(Resource<?> resource) {
    synchronized (currentPreviewOperations) {

        // Do the cleanup
        for (Iterator<PreviewOperation> i = currentPreviewOperations.iterator(); i.hasNext();) {
            PreviewOperation op = i.next();
            Resource<?> r = op.getResource();
            if (r.equals(resource)) {
                logger.debug("Preview creation of {} finished", r.getURI());
                i.remove();
                PreviewOperation o = previews.get(r.getURI());
                // In the meantime, someone may have canceled this operation and
                // created a new one
                if (op == o)
                    previews.remove(r.getURI());
                break;
            }
        }

        // Is there more work to do?
        if (!previewOperations.isEmpty() && currentPreviewOperations.size() < maxPreviewOperations) {

            // Get the next operation and do the bookkeeping
            PreviewOperation op = previewOperations.remove();
            Resource<?> r = op.getResource();
            currentPreviewOperations.add(op);

            // Finally start the generation
            PreviewGeneratorWorker previewWorker = new PreviewGeneratorWorker(this, r, environment,
                    op.getLanguages(), op.getStyles(), op.getFormat());
            op.setWorker(previewWorker);
            Thread t = new Thread(previewWorker);
            t.setPriority(Thread.MIN_PRIORITY);
            t.setDaemon(true);

            logger.debug("Starting creation of preview of {}", r.getURI());
            logger.trace("There are {} more preview operations waiting", previewOperations.size());
            logger.trace("Currently using {} out of {} preview creation slots", currentPreviewOperations.size(),
                    maxPreviewOperations);
            t.start();
        } else {
            logger.debug("No more resources queued for preview creation");
        }
    }
}

From source file:gda.device.detector.analyser.EpicsMCASimple.java

RegisterForEpicsUpdates(IEpicsDevice epicsDevice, List<EpicsRegistrationRequest> requests, IObserver observer) {
    this.epicsDevice = epicsDevice;
    this.requests = requests;
    this.observer = observer;
    Thread t = uk.ac.gda.util.ThreadManager.getThread(this);
    t.setPriority(java.lang.Thread.MIN_PRIORITY);
    t.start();/* ww w  .j  a v a  2  s. com*/
}

From source file:RhodesService.java

public static void installApplication(final String url) {
    Thread bgThread = new Thread(new Runnable() {
        public void run() {
            try {
                final RhodesService r = RhodesService.getInstance();
                final File tmpFile = r.downloadPackage(url);
                if (tmpFile != null) {
                    PerformOnUiThread.exec(new Runnable() {
                        public void run() {
                            try {
                                Logger.D(TAG, "Install package " + tmpFile.getAbsolutePath());
                                Uri uri = Uri.fromFile(tmpFile);
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                                r.startActivity(intent);
                            } catch (Exception e) {
                                Log.e(TAG, "Can't install file from " + tmpFile.getAbsolutePath(), e);
                                Logger.E(TAG, "Can't install file from " + tmpFile.getAbsolutePath() + ": "
                                        + e.getMessage());
                            }/*w ww  .j  a  va 2 s.  c  om*/
                        }
                    });
                }
            } catch (IOException e) {
                Log.e(TAG, "Can't download package from " + url, e);
                Logger.E(TAG, "Can't download package from " + url + ": " + e.getMessage());
            }
        }
    });
    bgThread.setPriority(Thread.MIN_PRIORITY);
    bgThread.start();
}

From source file:ti.modules.titanium.network.TiHTTPClient.java

public void send(Object userData) throws MethodNotSupportedException {
    aborted = false;/*from  www .java  2  s.c  o m*/

    // TODO consider using task manager
    int totalLength = 0;
    needMultipart = false;

    if (userData != null) {
        if (userData instanceof HashMap) {
            HashMap<String, Object> data = (HashMap) userData;
            boolean isPostOrPut = method.equals("POST") || method.equals("PUT");
            boolean isGet = !isPostOrPut && method.equals("GET");

            // first time through check if we need multipart for POST
            for (String key : data.keySet()) {
                Object value = data.get(key);

                if (value != null) {
                    // if the value is a proxy, we need to get the actual file object
                    if (value instanceof TiFileProxy) {
                        value = ((TiFileProxy) value).getBaseFile();
                    }

                    if (value instanceof TiBaseFile || value instanceof TiBlob) {
                        needMultipart = true;
                        break;
                    }
                }
            }

            boolean queryStringAltered = false;
            for (String key : data.keySet()) {
                Object value = data.get(key);
                if (isPostOrPut && (value != null)) {
                    // if the value is a proxy, we need to get the actual file object
                    if (value instanceof TiFileProxy) {
                        value = ((TiFileProxy) value).getBaseFile();
                    }

                    if (value instanceof TiBaseFile || value instanceof TiBlob) {
                        totalLength += addTitaniumFileAsPostData(key, value);

                    } else {
                        String str = TiConvert.toString(value);
                        addPostData(key, str);
                        totalLength += str.length();
                    }

                } else if (isGet) {
                    uri = uri.buildUpon().appendQueryParameter(key, TiConvert.toString(value)).build();
                    queryStringAltered = true;
                }
            }

            if (queryStringAltered) {
                this.url = uri.toString();
            }
        } else if (userData instanceof TiFileProxy || userData instanceof TiBaseFile
                || userData instanceof TiBlob) {
            Object value = userData;
            if (value instanceof TiFileProxy) {
                value = ((TiFileProxy) value).getBaseFile();
            }
            if (value instanceof TiBaseFile || value instanceof TiBlob) {
                setRawData(titaniumFileAsPutData(value));
            } else {
                setRawData(TiConvert.toString(value));
            }
        } else {
            setRawData(TiConvert.toString(userData));
        }
    }

    Log.d(TAG, "Instantiating http request with method='" + method + "' and this url:", Log.DEBUG_MODE);
    Log.d(TAG, this.url, Log.DEBUG_MODE);

    request = new DefaultHttpRequestFactory().newHttpRequest(method, this.url);
    request.setHeader(TITANIUM_ID_HEADER, TiApplication.getInstance().getAppGUID());
    for (String header : headers.keySet()) {
        request.setHeader(header, headers.get(header));
    }

    clientThread = new Thread(new ClientRunnable(totalLength),
            "TiHttpClient-" + httpClientThreadCounter.incrementAndGet());
    clientThread.setPriority(Thread.MIN_PRIORITY);
    clientThread.start();

    Log.d(TAG, "Leaving send()", Log.DEBUG_MODE);
}

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

private PendingLogTask[] journal(LogMessagingTask[] packets) {
    if (!ENABLE_JOURNALING)
        return new PendingLogTask[0]; // no error
    if (this.journaler.fos == null)
        return null; // error
    boolean amCoordinator = false, isAccept = false;
    PendingLogTask[] pending = new PendingLogTask[packets.length];
    for (int i = 0; i < packets.length; i++) {
        LogMessagingTask pkt = packets[i];
        amCoordinator = pkt.logMsg instanceof PValuePacket
                ? ((PValuePacket) pkt.logMsg).ballot.coordinatorID == myID
                : pkt.logMsg instanceof PreparePacket
                        ? ((PreparePacket) pkt.logMsg).ballot.coordinatorID == myID
                        : false;//from   w  w  w.j a va2s. c o m
        isAccept = pkt.logMsg.getType() == PaxosPacketType.ACCEPT;
        if (DONT_LOG_DECISIONS && !isAccept)
            continue;
        if (NON_COORD_ONLY && amCoordinator && !COORD_STRINGIFIES_WO_JOURNALING)
            continue;
        if (COORD_ONLY && !amCoordinator)
            continue;
        if (NON_COORD_DONT_LOG_DECISIONS && !amCoordinator && !isAccept)
            continue;
        if (COORD_DONT_LOG_DECISIONS && amCoordinator && !isAccept)
            continue;

        try {
            {
                byte[] bytes = !NO_STRINGIFY_JOURNALING && !(COORD_JOURNALS_WO_STRINGIFYING && amCoordinator)
                        ? toBytes(pkt.logMsg)
                        : Arrays.copyOf(testBytes, ((RequestPacket) pkt.logMsg).lengthEstimate());
                if (JOURNAL_COMPRESSION)
                    bytes = deflate(bytes);

                // format: <size><message>*
                ByteBuffer bbuf = ByteBuffer.allocate(4 + bytes.length);
                bbuf.putInt(bytes.length);
                bbuf.put(bytes);

                if (ALL_BUT_APPEND)
                    continue;

                if (STRINGIFY_WO_JOURNALING || (COORD_STRINGIFIES_WO_JOURNALING && amCoordinator))
                    continue;

                // else append to log file *after* creating pending task
                if (DB_INDEX_JOURNAL)
                    synchronized (this) {
                        SQLPaxosLogger.this.pendingLogMessages.add(pending[i] = new PendingLogTask(packets[i],
                                this.journaler.curLogfile, this.journaler.curLogfileSize, bytes.length));
                    }
                else if (PAUSABLE_INDEX_JOURNAL)
                    this.messageLog.add(packets[i].logMsg, this.journaler.curLogfile,
                            this.journaler.curLogfileSize, bytes.length);
                if (USE_MAP_DB && Util.oneIn(1000))
                    this.mapDB.dbMemory.commit();
                SQLPaxosLogger.this.journaler.appendToLogFile(bbuf.array(), pkt.logMsg.getPaxosID());
                assert (pending[i] == null
                        || this.journaler.curLogfileSize == pending[i].logfileOffset + bbuf.capacity());
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
            return null;
        }
    }

    if (this.journaler.curLogfileSize > MAX_LOG_FILE_SIZE) {
        // always commit pending before rolling log file
        log.log(Level.FINE, "{0} rolling log file {1}",
                new Object[] { SQLPaxosLogger.this.journaler, SQLPaxosLogger.this.journaler.curLogfile });
        // DelayProfiler.updateMovAvg("#fgsync",
        // this.pendingLogMessages.size());
        // first sync, then roll log file
        SQLPaxosLogger.this.syncLogMessagesIndex();
        long t = System.currentTimeMillis();
        SQLPaxosLogger.this.journaler.rollLogFile();
        DelayProfiler.updateDelay("rolllog", t, 1.0);

        if (this.journaler.shouldGC()) {
            this.GC.submit(new TimerTask() {
                @Override
                public void run() {
                    try {
                        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
                        SQLPaxosLogger.this
                                .garbageCollectJournal(SQLPaxosLogger.this.journaler.getGCCandidates());
                    } catch (Exception | Error e) {
                        log.severe(this + " incurred exception " + (e.getMessage() != null ? e.getMessage() : e)
                                + " while garbage collecting logfiles");
                        e.printStackTrace();
                    }
                }
            }, 0);
        }
    }
    if (!DB_INDEX_JOURNAL && Util.oneIn(Integer.MAX_VALUE))
        // used only for testing
        SQLPaxosLogger.deleteOldCheckpoints(logDirectory, SQLPaxosLogger.this.journaler.logfilePrefix, 5, this);

    return pending;
}

From source file:program.RunProgram.java

/**
 * Kill the current thread//ww w  . j  a  v  a  2 s . c  o  m
 * @return True if Succes
 */
public boolean KillThread() {
    try {
        //--Set flag to tell the thread that we cancel
        cancel = true;
        //--Try to kill this program if it is still running...
        //--Note: duplicate from what we found in programs class
        if (properties.getStatus() == status_running) {
            killer k = new killer(properties);
        }
        //--Lower this thread properties... So that that the system become more responsible
        thread.setPriority(Thread.MIN_PRIORITY);
        //--Destroy any remaining process
        if (p != null)
            p.destroy();
        if (thread != null)
            thread.interrupt();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}