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:org.infoglue.deliver.applications.actions.ViewPageAction.java

/**
 * This method is the application entry-point. The parameters has been set through the setters
 * and now we just have to render the appropriate output. 
 *///from  w w  w .ja  va  2  s.c o m

public String doExecute() throws Exception {
    if (isRecacheCall) {
        //logger.warn("ThreadId:" + Thread.currentThread().getName());
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    }

    //TODO - Can this be removed perhaps
    while (CmsPropertyHandler.getActuallyBlockOnBlockRequests()
            && RequestAnalyser.getRequestAnalyser().getBlockRequests()) {
        //logger.info("Queing up requests as cache eviction are taking place..");
        Thread.sleep(10);
    }

    try {
        Integer maxActiveRequests = new Integer(CmsPropertyHandler.getMaxActiveRequests());
        Integer maxRequestTime = new Integer(CmsPropertyHandler.getMaxRequestTime());
        //logger.info("maxActiveRequests:" + maxActiveRequests + "-" + maxRequestTime);

        while (CmsPropertyHandler.getUseHighLoadLimiter().equalsIgnoreCase("true")
                && RequestAnalyser.getRequestAnalyser().getNumberOfActiveRequests() > maxActiveRequests
                        .intValue()
                && (lastRequestProcessingTime > maxRequestTime.intValue() || maxRequestTime.intValue() < 1)) {
            if (logger.isInfoEnabled())
                logger.info("Queing up...:" + RequestAnalyser.getRequestAnalyser().getNumberOfActiveRequests()
                        + "(" + RequestAnalyser.getRequestAnalyser().getNumberOfCurrentRequests() + ") - "
                        + lastRequestProcessingTime);

            int sleepTime = random.nextInt(300);
            //logger.info("Queing up...:" + RequestAnalyser.getRequestAnalyser().getNumberOfActiveRequests() + "(" + RequestAnalyser.getRequestAnalyser().getNumberOfCurrentRequests() + ") - " + lastRequestProcessingTime + " for " + sleepTime + " ms");

            Thread.sleep(sleepTime);
        }
    } catch (Exception e) {
        logger.error(
                "You have faulty settings in either maxActiveRequests or maxRequestTime - fix this as it affects performance:"
                        + e.getMessage(),
                e);
    }

    if (logger.isInfoEnabled()) {
        logger.info("************************************************");
        logger.info("* ViewPageAction was called....                *");
        logger.info("************************************************");
    }

    HttpServletRequest request = getRequest();
    if (!CmsPropertyHandler.getOperatingMode().equals("3"))
        tk = new ThreadMonitor(new Long(CmsPropertyHandler.getDeliverRequestTimeout()).longValue(), request,
                "Page view took to long!", true);
    else {
        if (!CmsPropertyHandler.getKillLiveRequestWhichTimedout())
            tk = new ThreadMonitor(new Long(CmsPropertyHandler.getLiveDeliverRequestTimeout()).longValue(),
                    request, "Page view seems to take to long!", false);
        else
            tk = new ThreadMonitor(new Long(CmsPropertyHandler.getLiveDeliverRequestTimeout()).longValue(),
                    request, "Page view took to long!", true);
    }

    RequestAnalyser.getRequestAnalyser().incNumberOfCurrentRequests(tk);

    long start = System.currentTimeMillis();
    long elapsedTime = 0;

    DatabaseWrapper dbWrapper = new DatabaseWrapper(CastorDatabaseService.getDatabase());

    beginTransaction(dbWrapper.getDatabase());

    try {
        validateAndModifyInputParameters(dbWrapper.getDatabase());

        this.nodeDeliveryController = NodeDeliveryController.getNodeDeliveryController(this.siteNodeId,
                this.languageId, this.contentId);
        this.integrationDeliveryController = IntegrationDeliveryController
                .getIntegrationDeliveryController(this.siteNodeId, this.languageId, this.contentId);

        boolean isUserRedirected = false;
        Integer protectedSiteNodeVersionId = this.nodeDeliveryController
                .getProtectedSiteNodeVersionIdForPageCache(dbWrapper.getDatabase(), siteNodeId);
        Integer forceProtocolChangeSetting = this.nodeDeliveryController
                .getForceProtocolChangeSettingForPageCache(dbWrapper.getDatabase(), siteNodeId);

        if (logger.isInfoEnabled())
            logger.info("protectedSiteNodeVersionId:" + protectedSiteNodeVersionId);

        String protectWorking = CmsPropertyHandler.getProtectDeliverWorking();
        String protectPreview = CmsPropertyHandler.getProtectDeliverPreview();
        boolean protectDeliver = false;

        if (protectWorking.equals("true") && CmsPropertyHandler.getOperatingMode().equals("0"))
            protectDeliver = true;
        else if (protectPreview.equals("true") && CmsPropertyHandler.getOperatingMode().equals("2"))
            protectDeliver = true;

        isUserRedirected = handleAccessBasedProtocolRedirect(protectedSiteNodeVersionId, this.repositoryId,
                forceProtocolChangeSetting, dbWrapper.getDatabase());

        if (!isUserRedirected) {
            if (logger.isInfoEnabled())
                logger.info("RemoteAddress:" + getRequest().getRemoteAddr());

            if (CmsPropertyHandler.getAllowInternalCallsBasedOnIP()) {
                if (getRequest().getRemoteAddr().equals("127.0.0.1")
                        || getRequest().getRemoteAddr().equals("192.168.0.1"))
                    protectDeliver = false;
            }

            if (protectedSiteNodeVersionId != null || protectDeliver) {
                if (logger.isInfoEnabled()) {
                    logger.info("protectedSiteNodeVersionId:" + protectedSiteNodeVersionId);
                    logger.info("protectDeliver:" + protectDeliver);
                }

                isUserRedirected = handleExtranetLogic(dbWrapper.getDatabase(), this.repositoryId,
                        protectedSiteNodeVersionId, protectDeliver, false);
            } else {
                String forceIdentityCheck = RepositoryDeliveryController.getRepositoryDeliveryController()
                        .getExtraPropertyValue(this.repositoryId, "forceIdentityCheck");
                if (logger.isInfoEnabled())
                    logger.info("forceIdentityCheck:" + forceIdentityCheck);
                if (CmsPropertyHandler.getForceIdentityCheck().equalsIgnoreCase("true")
                        || (forceIdentityCheck != null && forceIdentityCheck.equalsIgnoreCase("true"))) {
                    boolean isForcedIdentityCheckDisabled = this.nodeDeliveryController
                            .getIsForcedIdentityCheckDisabled(dbWrapper.getDatabase(), this.siteNodeId);
                    if (logger.isInfoEnabled())
                        logger.info("isForcedIdentityCheckDisabled:" + isForcedIdentityCheckDisabled);
                    if (!isForcedIdentityCheckDisabled) {
                        isUserRedirected = handleExtranetLogic(dbWrapper.getDatabase(), true);
                    }
                }
            }
        }

        String pageKey = this.nodeDeliveryController.getPageCacheKey(dbWrapper.getDatabase(),
                this.getHttpSession(), getRequest(), this.siteNodeId, this.languageId, this.contentId,
                browserBean.getUseragent(), this.getRequest().getQueryString(), "");

        if (logger.isInfoEnabled())
            logger.info("pageKey:" + pageKey);

        templateController = getTemplateController(dbWrapper, getSiteNodeId(), getLanguageId(), getContentId(),
                getRequest(), (InfoGluePrincipal) this.principal, false);

        if (logger.isInfoEnabled())
            logger.info("handled extranet users: " + isUserRedirected);

        // ----
        // -- portlet
        // ----

        // -- check if the portal is active
        String portalEnabled = CmsPropertyHandler.getEnablePortal();
        boolean portalActive = ((portalEnabled != null) && portalEnabled.equals("true"));

        if (portalActive && !isRecacheCall) {
            if (logger.isInfoEnabled())
                logger.info("---> Checking for portlet action");

            PortalService service = new PortalService();
            //TODO: catch PortalException?
            boolean actionExecuted = service.service(getRequest(), getResponse());

            // -- if an action was executed return NONE as a redirect is issued
            if (actionExecuted) {
                if (logger.isInfoEnabled())
                    logger.info(
                            "---> PortletAction was executed, returning NONE as a redirect has been issued");
                isUserRedirected = true;
                return NONE;
            }
        }

        if (logger.isInfoEnabled())
            logger.info("handled portal action: " + isUserRedirected);

        if (!isUserRedirected) {
            if (logger.isInfoEnabled())
                logger.info("this.templateController.getPrincipal():" + templateController.getPrincipal());

            DeliveryContext deliveryContext = DeliveryContext.getDeliveryContext(true);
            deliveryContext.setRepositoryName(this.repositoryName);
            deliveryContext.setSiteNodeId(this.siteNodeId);
            deliveryContext.setContentId(this.contentId);
            deliveryContext.setLanguageId(this.languageId);
            deliveryContext.setPageKey(pageKey);
            //deliveryContext.setSession(this.getSession());
            //deliveryContext.setInfoGlueAbstractAction(this);
            deliveryContext.setHttpServletRequest(this.getRequest());
            deliveryContext.setHttpServletResponse(this.getResponse());
            deliveryContext.setUseFullUrl(Boolean.parseBoolean(CmsPropertyHandler.getUseDNSNameInURI()));

            SiteNodeTypeDefinitionVO siteNodeTypeDefinitionVO = getSiteNodeTypeDefinition(this.siteNodeId,
                    dbWrapper.getDatabase());

            try {
                String invokerClassName = siteNodeTypeDefinitionVO.getInvokerClassName();
                PageInvoker pageInvoker = (PageInvoker) Class.forName(invokerClassName).newInstance();
                pageInvoker.setParameters(dbWrapper, this.getRequest(), this.getResponse(), templateController,
                        deliveryContext);
                pageInvoker.deliverPage();

                request.setAttribute("progress", "after pageInvoker was called");
            } catch (ClassNotFoundException e) {
                throw new SystemException(
                        "An error was thrown when trying to use the page invoker class assigned to this page type:"
                                + e.getMessage(),
                        e);
            } finally {
                deliveryContext.clear();
                deliveryContext = null;
            }
        }

        //StatisticsService.getStatisticsService().registerRequest(getRequest(), getResponse(), pagePath, elapsedTime);
        //logger.info("Registered request in statistics service");
    } catch (PageNotFoundException e) {
        String extraInformation = "Original URL: " + getOriginalFullURL() + "\n";
        extraInformation += "Referer: " + getRequest().getHeader("Referer") + "\n";
        extraInformation += "UserAgent: " + getRequest().getHeader("User-Agent") + "\n";
        extraInformation += "User IP: " + getRequest().getRemoteAddr();

        logger.warn("A user requested a non existing page:" + e.getMessage() + "\n" + extraInformation);
        rollbackTransaction(dbWrapper.getDatabase());

        getResponse().setContentType("text/html; charset=UTF-8");
        getRequest().setAttribute("responseCode", "404");
        getRequest().setAttribute("error", e);
        getRequest().setAttribute("errorUrl", getErrorUrl());
        getRequest().getRequestDispatcher("/ErrorPage.action").forward(getRequest(), getResponse());
    } catch (NoBaseTemplateFoundException e) {
        String extraInformation = "Original URL: " + getOriginalFullURL() + "\n";
        extraInformation += "Referer: " + getRequest().getHeader("Referer") + "\n";
        extraInformation += "UserAgent: " + getRequest().getHeader("User-Agent") + "\n";
        extraInformation += "User IP: " + getRequest().getRemoteAddr();

        logger.error(
                "A user requested a page which had no base template (probably of the old HTMLPageInvoker type - should be changed):"
                        + e.getMessage() + "\n" + extraInformation);
        rollbackTransaction(dbWrapper.getDatabase());

        getResponse().setContentType("text/html; charset=UTF-8");
        getRequest().setAttribute("responseCode", "500");
        getRequest().setAttribute("error", e);
        getRequest().setAttribute("errorUrl", getErrorUrl());
        getRequest().getRequestDispatcher("/ErrorPage.action").forward(getRequest(), getResponse());
    } catch (IOException e) {
        String extraInformation = "Original URL: " + getOriginalFullURL() + "\n";
        extraInformation += "Referer: " + getRequest().getHeader("Referer") + "\n";
        extraInformation += "UserAgent: " + getRequest().getHeader("User-Agent") + "\n";
        extraInformation += "User IP: " + getRequest().getRemoteAddr();

        if (e.getCause() != null) {
            if (e.getCause() instanceof SocketException)
                logger.warn("A io exception was thrown returning data to client:" + e.getCause().getMessage()
                        + "\n" + extraInformation);
            else
                logger.error("A io exception was thrown returning data to client:" + e.getCause().getMessage()
                        + "\n" + extraInformation);
        } else
            logger.error("A io exception was thrown returning data to client:" + e.getMessage() + "\n"
                    + extraInformation);
        rollbackTransaction(dbWrapper.getDatabase());
    } catch (Exception e) {
        String extraInformation = "Original URL: " + getOriginalFullURL() + "\n";
        extraInformation += "Referer: " + getRequest().getHeader("Referer") + "\n";
        extraInformation += "UserAgent: " + getRequest().getHeader("User-Agent") + "\n";
        extraInformation += "User IP: " + getRequest().getRemoteAddr();

        if (e instanceof java.net.SocketException
                || e.getCause() != null && e.getCause() instanceof java.net.SocketException)
            logger.error("An error occurred so we should not complete the transaction:" + e.getMessage() + "\n"
                    + extraInformation);
        else
            logger.error("An error occurred so we should not complete the transaction:" + e.getMessage() + "\n"
                    + extraInformation, e);

        rollbackTransaction(dbWrapper.getDatabase());

        getResponse().setContentType("text/html; charset=UTF-8");
        getRequest().setAttribute("responseCode", "500");
        getRequest().setAttribute("error", e);
        getRequest().setAttribute("errorUrl", getErrorUrl());
        getRequest().getRequestDispatcher("/ErrorPage.action").forward(getRequest(), getResponse());
    } finally {
        if (logger.isInfoEnabled())
            logger.info("Before closing transaction");

        try {
            closeTransaction(dbWrapper.getDatabase());
        } catch (Exception e) {
            logger.error("Problem closing connection:" + e.getMessage(), e);
        }

        try {
            if (templateController != null) {
                templateController.clear();
                templateController = null;
            }
        } catch (Exception e) {
            logger.error("Problem clearing:" + e.getMessage(), e);
        }

        if (logger.isInfoEnabled())
            logger.info("After closing transaction");

        elapsedTime = Math.abs(System.currentTimeMillis() - start);
        RequestAnalyser.getRequestAnalyser().decNumberOfCurrentRequests(elapsedTime);
        lastRequestProcessingTime = elapsedTime;

        //System.out.println("The page delivery took " + elapsedTime + "ms for request " + this.getRequest().getRequestURL() + "?" + this.getRequest().getQueryString());
        if (!memoryWarningSent) {
            float memoryLeft = ((float) Runtime.getRuntime().maxMemory()
                    - (float) Runtime.getRuntime().totalMemory()) / 1024f / 1024f;
            float percentLeft = (memoryLeft / ((float) Runtime.getRuntime().maxMemory() / 1024f / 1024f))
                    * 100f;
            float percentLeft2 = ((float) Runtime.getRuntime().freeMemory()
                    / (float) Runtime.getRuntime().totalMemory()) * 100f;

            if (percentLeft < 15 && percentLeft2 < 15) {
                memoryWarningSent = true;
                String subject = "Memory is getting low on " + CmsPropertyHandler.getServerName();
                String mailBody = "The java maximum heap size is almost used up - only " + (int) memoryLeft
                        + "MB (" + (int) percentLeft
                        + "%) left. Increase the max heap size if possible or trim the cache sizes if they are very large.";
                String warningEmailReceiver = CmsPropertyHandler.getWarningEmailReceiver();
                if (warningEmailReceiver != null && !warningEmailReceiver.equals("")
                        && warningEmailReceiver.indexOf("@warningEmailReceiver@") == -1) {
                    try {
                        logger.warn("Sending warning mail:" + (int) percentLeft + ":" + (int) memoryLeft + ":"
                                + Runtime.getRuntime().maxMemory() / 1024 / 1024);
                        MailServiceFactory.getService().sendEmail("text/html", warningEmailReceiver,
                                warningEmailReceiver, null, null, null, null, subject, mailBody, "utf-8");
                    } catch (Exception e) {
                        logger.error("Could not send mail:" + e.getMessage(), e);
                    }
                }
            }
        }

        String originalFullUrl = getOriginalFullURL();
        if (elapsedTime > 1000)
            RequestAnalyser.getRequestAnalyser().registerPageStatistics("" + originalFullUrl, elapsedTime);

        //System.out.println("The page delivery took " + elapsedTime + "ms");
        if (elapsedTime > 10000) {
            logger.warn("The page delivery took " + elapsedTime + "ms for request " + originalFullUrl);
            logger.warn("The memory consumption was "
                    + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + "("
                    + Runtime.getRuntime().totalMemory() + "/" + Runtime.getRuntime().maxMemory() + ") bytes");
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("The page delivery took " + elapsedTime + "ms");
                logger.info("The memory consumption was "
                        + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + "("
                        + Runtime.getRuntime().totalMemory() + "/" + Runtime.getRuntime().maxMemory()
                        + ") bytes");
            }
        }

        if (tk != null && !tk.getIsDoneRunning())
            tk.done();
        else
            logger.warn("Done had allready been run... skipping");
    }

    return NONE;
}

From source file:it.imwatch.nfclottery.MainActivity.java

@Override
protected void onResume() {
    super.onResume();
    // It's important that the Activity is in the foreground (resumed) when we
    // setup the dispatching. If it's not, this will throw an IllegalStateException.
    setupForegroundDispatch(this, mNfcAdapter);

    updateNfcUi();//ww  w.  ja  va  2  s.co  m

    // Start checking the NFC status periodically
    mNfcCheckerThread = new Thread(mNfcChecker);
    mNfcCheckerThread.setName("NfcChecker");
    mNfcCheckerThread.setPriority(Thread.MIN_PRIORITY);
    mNfcCheckerThread.start();
}

From source file:tw.edu.sju.ee.eea.module.iepe.project.window.IepeRealtimeVoltageElement.java

@Override
public void run() {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    while (!Thread.interrupted()) {
        if (!hold) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).update(t);/*from   w  w w  .ja va 2s.c  o  m*/
                //                    channels[i].update(t);
            }
            //                channels[0].series.setNotify(true);
            //                channels[0].series.setNotify(false);
            new Thread() {

                @Override
                public void run() {
                    ((SourceChannel) list.get(0)).series.changed();
                }

            }.start();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}

From source file:com.cyclopsgroup.tornado.security.impl.DefaultSecurityService.java

/**
 * Override method start in class DefaultSecurityService
 *
 * @see org.apache.avalon.framework.activity.Startable#start()
 *///from   ww  w.  j a v a 2  s.co m
public void start() throws Exception {
    checkTimeoutThread = new Thread() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(10000);
                    checkTimeout();
                } catch (InterruptedException e) {
                    break;
                }
            }
        }
    };
    checkTimeoutThread.setDaemon(true);
    checkTimeoutThread.setPriority(Thread.MIN_PRIORITY);
    checkTimeoutThread.start();
}

From source file:com.datos.vfs.impl.DefaultFileMonitor.java

/**
 * Starts monitoring the files that have been added.
 *//*w  ww. j a v  a 2 s.  com*/
public void start() {
    if (this.monitorThread == null) {
        this.monitorThread = new Thread(this);
        this.monitorThread.setDaemon(true);
        this.monitorThread.setPriority(Thread.MIN_PRIORITY);
    }
    this.monitorThread.start();
}

From source file:com.ubuntuone.android.files.service.UpDownService.java

/** Lazily initialize the upload worker thread. */
private void uploaderLazyInit() {
    if (uploadWorker == null) {
        uploadWorker = new UploadWorker();
        uploadWorker.setPriority(Thread.MIN_PRIORITY);
        uploadWorker.start();/*w ww.  j  ava2s .  c o m*/
        synchronized (this) {
            try {
                wait(1000);
            } catch (InterruptedException e) {
            }
        }
    }
}

From source file:org.metis.sql.SqlJob.java

/**
 * Starts the internal thread./*from   ww w  . java  2 s .co  m*/
 * 
 * @throws Exception
 */
public synchronized void doStart() {
    if (getRunner() != null && isStarted()) {
        return;
    }
    setRunner(new Thread(this, getThreadName()));
    getRunner().setDaemon(true);
    getRunner().setPriority(Thread.MIN_PRIORITY);
    getRunner().start();
}

From source file:net.xmind.workbench.internal.notification.SiteEventNotificationService.java

private void showNotifications(final List<ISiteEvent> events) {
    if (workbench == null)
        return;/*from w  w  w.  jav  a2  s  .  com*/
    if (canShowNotifications()) {
        doShowNotifications(events);
    } else {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                while (!canShowNotifications()) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        return;
                    }
                }
                doShowNotifications(events);
            }
        });
        thread.setPriority(Thread.MIN_PRIORITY);
        thread.setDaemon(true);
        thread.setName("WaitToShowNotifications"); //$NON-NLS-1$
        thread.start();
    }
}

From source file:org.opendedup.collections.ProgressiveFileBasedCSMap.java

@Override
public synchronized long claimRecords(SDFSEvent evt, LargeBloomFilter bf) throws IOException {
    if (this.isClosed())
        throw new IOException("Hashtable " + this.fileName + " is close");
    executor = new ThreadPoolExecutor(Main.writeThreads + 1, Main.writeThreads + 1, 10, TimeUnit.SECONDS,
            worksQueue, new ProcessPriorityThreadFactory(Thread.MIN_PRIORITY), executionHandler);
    csz = new AtomicLong(0);

    try {/*from w  w  w. j  a v a 2  s. c  o  m*/
        Lock l = this.gcLock.writeLock();
        l.lock();
        this.runningGC = true;
        try {
            File _fs = new File(fileName);
            lbf = new LargeBloomFilter(_fs.getParentFile(), maxSz, .01, true, true, false);
        } finally {
            l.unlock();
        }
        SDFSLogger.getLog().info("Claiming Records [" + this.getSize() + "] from [" + this.fileName + "]");
        SDFSEvent tEvt = SDFSEvent
                .claimInfoEvent("Claiming Records [" + this.getSize() + "] from [" + this.fileName + "]", evt);
        tEvt.maxCt = this.maps.size();
        Iterator<AbstractShard> iter = maps.iterator();
        ArrayList<ClaimShard> excs = new ArrayList<ClaimShard>();
        while (iter.hasNext()) {
            tEvt.curCt++;
            AbstractShard m = null;
            try {
                m = iter.next();
                ClaimShard cms = new ClaimShard(m, bf, lbf, csz);
                excs.add(cms);
                executor.execute(cms);
            } catch (Exception e) {
                tEvt.endEvent("Unable to claim records for " + m + " because : [" + e.toString() + "]",
                        SDFSEvent.ERROR);
                SDFSLogger.getLog().error("Unable to claim records for " + m, e);
                throw new IOException(e);
            }
        }
        executor.shutdown();
        try {
            while (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                SDFSLogger.getLog().debug("Awaiting fdisk completion of threads.");
            }
        } catch (InterruptedException e) {
            throw new IOException(e);
        }
        for (ClaimShard cms : excs) {
            if (cms.ex != null)
                throw new IOException(cms.ex);
        }
        this.kSz.getAndAdd(-1 * csz.get());
        tEvt.endEvent("removed [" + csz.get() + "] records");
        SDFSLogger.getLog().info("removed [" + csz.get() + "] records");
        iter = maps.iterator();
        while (iter.hasNext()) {
            AbstractShard m = null;
            try {
                m = iter.next();
                if (!m.isFull() && !m.isActive()) {

                    // SDFSLogger.getLog().info("deleting " +
                    // m.toString());
                    m.iterInit();
                    KVPair p = m.nextKeyValue();
                    while (p != null) {
                        ProgressiveFileByteArrayLongMap _m = this.getWriteMap();
                        try {
                            _m.put(p.key, p.value);
                            this.lbf.put(p.key);
                            p = m.nextKeyValue();
                        } catch (HashtableFullException e) {

                        }

                    }
                    int mapsz = maps.size();
                    l = this.gcLock.writeLock();
                    l.lock();
                    try {
                        maps.remove(m);
                    } finally {
                        l.unlock();
                    }
                    mapsz = mapsz - maps.size();
                    SDFSLogger.getLog()
                            .info("removing map " + m.toString() + " sz=" + maps.size() + " rm=" + mapsz);
                    m.vanish();

                    m = null;
                } else if (m.isMaxed()) {
                    SDFSLogger.getLog().info("deleting maxed " + m.toString());
                    m.iterInit();
                    KVPair p = m.nextKeyValue();
                    while (p != null) {
                        ProgressiveFileByteArrayLongMap _m = this.getWriteMap();
                        try {
                            _m.put(p.key, p.value);
                            p = m.nextKeyValue();
                        } catch (HashtableFullException e) {

                        }

                    }
                    int mapsz = maps.size();
                    l = this.gcLock.writeLock();
                    l.lock();
                    try {
                        maps.remove(m);
                    } finally {
                        l.unlock();
                    }
                    mapsz = mapsz - maps.size();
                    SDFSLogger.getLog()
                            .info("removing map " + m.toString() + " sz=" + maps.size() + " rm=" + mapsz);
                    m.vanish();

                    m = null;
                }
            } catch (Exception e) {
                tEvt.endEvent("Unable to compact " + m + " because : [" + e.toString() + "]", SDFSEvent.ERROR);
                SDFSLogger.getLog().error("to compact " + m, e);
                throw new IOException(e);
            }
        }
        l.lock();
        this.runningGC = false;
        l.unlock();
        return csz.get();
    } finally {
        executor = null;
    }
}

From source file:mobisocial.musubi.service.AppUpdaterService.java

@Override
public void onCreate() {
    mDatabaseSource = App.getDatabaseSource(this);
    mThread = new HandlerThread("AppManifests");
    mThread.setPriority(Thread.MIN_PRIORITY);
    mThread.start();//w  ww. j  a v a 2  s.c  o m
    mAppManager = new AppManager(mDatabaseSource);
    mUpdateHandler = new Handler(mThread.getLooper());
    ContentResolver resolver = getContentResolver();
    resolver.registerContentObserver(MusubiService.UPDATE_APP_MANIFESTS, false, new UpdateApps(mUpdateHandler));

    //kick it off once per boot
    resolver.notifyChange(MusubiService.UPDATE_APP_MANIFESTS, null);
    Log.w(TAG, "service is now running");
}