Example usage for java.util.concurrent.locks Lock unlock

List of usage examples for java.util.concurrent.locks Lock unlock

Introduction

In this page you can find the example usage for java.util.concurrent.locks Lock unlock.

Prototype

void unlock();

Source Link

Document

Releases the lock.

Usage

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

/**
 * Process failover of new master for entityGroup
 * <code>encodedEntityGroupName</code> up in zookeeper.
 *
 * @param encodedEntityGroupName/*  www .  j  a  v  a 2 s.  com*/
 *          EntityGroup to process failover for.
 * @param entityGroupInfo
 *          If null we'll go get it from meta table.
 * @return True if we processed <code>entityGroupInfo</code> as a EGIT.
 * @throws org.apache.zookeeper.KeeperException
 * @throws java.io.IOException
 */
boolean processEntityGroupInTransition(final String encodedEntityGroupName,
        final EntityGroupInfo entityGroupInfo) throws KeeperException, IOException {
    // We need a lock here to ensure that we will not put the same entityGroup
    // twice
    // It has no reason to be a lock shared with the other operations.
    // We can do the lock on the entityGroup only, instead of a global lock:
    // what we want to ensure
    // is that we don't have two threads working on the same entityGroup.
    Lock lock = locker.acquireLock(encodedEntityGroupName);
    try {
        Stat stat = new Stat();
        byte[] data = ZKAssign.getDataAndWatch(watcher, encodedEntityGroupName, stat);
        if (data == null)
            return false;
        EntityGroupTransaction rt;
        try {
            rt = EntityGroupTransaction.parseFrom(data);
        } catch (DeserializationException e) {
            LOG.warn("Failed parse znode data", e);
            return false;
        }
        EntityGroupInfo egInfo = entityGroupInfo;
        if (egInfo == null) {
            egInfo = entityGroupStates.getEntityGroupInfo(rt.getEntityGroupName());
            if (egInfo == null)
                return false;
        }
        processEntityGroupsInTransition(rt, egInfo, stat.getVersion());
        return true;
    } finally {
        lock.unlock();
    }
}

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

private AbstractShard getReadMap(byte[] hash, boolean deep) throws IOException {
    Lock l = gcLock.readLock();
    l.lock();/*from w w w.j  a va 2  s  .com*/
    ct.incrementAndGet();
    try {

        if (!runningGC && !lbf.mightContain(hash)) {
            // SDFSLogger.getLog().info("not in bloom filter");
            return null;
        }

        /*
         * Iterator<ProgressiveFileByteArrayLongMap> iter =
         * activeReadMaps.iterator(); while (iter.hasNext()) {
         * ProgressiveFileByteArrayLongMap _m = iter.next(); if
         * (_m.containsKey(hash)) return _m; }
         */
        zmt.incrementAndGet();
        AbstractShard _km;
        _km = this.keyLookup.getIfPresent(new ByteArrayWrapper(hash));
        if (_km != null && !_km.isClosed()) {
            if (!_km.isClosed()) {
                // long chl = ch.incrementAndGet();
                // SDFSLogger.getLog().info("found ch=" + chl + " sz=" +
                // this.keyLookup.size());
                _km.cache();
                return _km;
            } else {
                this.keyLookup.invalidate(new ByteArrayWrapper(hash));
            }
        }

        /*
        synchronized (ct) {
           if (ct.get() > 10000) {
              SDFSLogger.getLog().info("misses=" + mt.get() + " inserts=" + ct.get() + " lookups=" + amt.get()
             + " attempts=" + zmt.incrementAndGet());
              ct.set(0);
              amt.set(0);
              mt.set(0);
           }
        }
        */

        int sns = this.maxTbls;
        int trs = 0;
        if (this.maxTbls <= 0)
            deep = true;
        for (AbstractShard _m : this.maps.getAL()) {
            trs++;
            if (!deep && trs == this.maxTbls) {
                sns = this.tblrnd.nextInt(0, this.maps.size());
            }
            if (!deep && trs > sns) {
                break;
            }
            amt.incrementAndGet();
            try {
                if (_m.containsKey(hash)) {
                    this.keyLookup.put(new ByteArrayWrapper(hash), _m);
                    _m.cache();
                    return _m;
                }
            } catch (MapClosedException e) {
                getReadMap(hash, deep);
            }
        }
        mt.incrementAndGet();

        return null;

    } finally {
        l.unlock();
    }

}

From source file:net.siegmar.japtproxy.misc.IOHandler.java

/**
 * This method is responsible for fetching remote data (if needed) and
 * sending the data (locally stored, or remotely fetched) to the client.
 *
 * @param requestedData  the requested data
 * @param poolObject     the pool object
 * @param targetResource the remote resource link
 * @param res            the HttpServletResponse object
 * @return true if the file was sent from cache, false otherwise
 * @throws IOException is thrown if a problem occured while sending data
 * @throws net.siegmar.japtproxy.exception.ResourceUnavailableException is thrown if the resource was not found
 *///from  www  . j  a  v  a  2 s  .  c o m
public boolean sendAndSave(final RequestedData requestedData, final PoolObject poolObject,
        final URL targetResource, final HttpServletResponse res)
        throws IOException, ResourceUnavailableException, InitializationException {
    final String lockIdentifier = requestedData.getRequestedResource();
    final ReadWriteLock lock = ResourceLock.obtainLocker(lockIdentifier);
    final Lock readLock = lock.readLock();

    LockStatus lockStatus;

    readLock.lock();
    lockStatus = LockStatus.READ;

    LOG.debug("Obtained readLock for '{}'", lockIdentifier);

    final long poolModification = poolObject.getLastModified();

    FetchedResource fetchedResource = null;
    OutputStream saveOs = null;
    InputStream is = null;

    try {
        if (poolModification != 0) {
            if (!isNewVersionCheckRequired(poolObject, requestedData.getRequestedResource())) {
                LOG.debug("Local object exists and no need to do a version check - sending local object");
                sendLocalFile(poolObject, requestedData.getRequestModifiedSince(), res);
                return true;
            }

            LOG.debug("Local object exists but new version check is required");
        } else {
            LOG.debug("No local object exists - requesting remote host");
        }

        // Get a fetcher (http, ftp) for the current targetResource
        final Fetcher fetcher = fetcherPool.getInstance(targetResource);

        if (fetcher == null) {
            throw new InitializationException("No fetcher found for resource '" + targetResource + "'");
        }

        fetchedResource = fetcher.fetch(targetResource, poolModification, requestedData.getUserAgent());

        final String contentType = fetchedResource.getContentType();
        final long remoteModification = fetchedResource.getLastModified();
        final long contentLength = fetchedResource.getContentLength();

        if (remoteModification != 0 && poolModification > remoteModification) {
            LOG.warn(
                    "Remote object is older than local pool object "
                            + "(Remote timestamp: {} - Local timestamp: {}). "
                            + "Object won't get updated! Check this manually!",
                    Util.getSimpleDateFromTimestamp(remoteModification),
                    Util.getSimpleDateFromTimestamp(poolModification));
        }

        setHeader(res, fetchedResource);

        if (!fetchedResource.isModified()) {
            LOG.debug("Remote resource has no new version - sending local object");
            sendLocalFile(poolObject, requestedData.getRequestModifiedSince(), res);
            return true;
        }

        if (LOG.isDebugEnabled()) {
            if (poolModification != 0) {
                // Pool file exists, but it is out of date
                LOG.debug(
                        "Newer version found (old Last-Modified: {}) - Request '{}', Last-Modified: {}, "
                                + "Content-Type: {}, Content-Length: {}",
                        Util.getSimpleDateFromTimestamp(poolModification), targetResource,
                        Util.getSimpleDateFromTimestamp(remoteModification), contentType, contentLength);
            } else {
                // No pool file exists
                LOG.debug("Request '{}', Last-Modified: {}, Content-Type: {}, Content-Length: {}",
                        targetResource, Util.getSimpleDateFromTimestamp(remoteModification), contentType,
                        contentLength);
            }
        }

        readLock.unlock();
        lock.writeLock().lock();
        lockStatus = LockStatus.WRITE;

        LOG.debug("Obtained writeLock for '{}'", lockIdentifier);

        is = fetchedResource.getInputStream();

        LOG.info("Sending remote object '{}'", poolObject.getName());

        saveOs = new TeeOutputStream(poolObject.getOutputStream(), res.getOutputStream());
        final long bytesCopied = IOUtils.copyLarge(is, saveOs);

        LOG.debug("Data sent to file and client");

        poolObject.setLastModified(remoteModification);

        if (contentLength != -1 && bytesCopied != contentLength) {
            throw new IOException(
                    String.format("Received file has invalid file size - " + "only %d of %d were downloaded",
                            bytesCopied, contentLength));
        }

        poolObject.store();

        return false;
    } catch (final IOException e) {
        // Remove pool file if it was created by this thread
        if (poolModification == 0) {
            poolObject.remove();
        }

        throw e;
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(saveOs);

        if (fetchedResource != null) {
            fetchedResource.close();
        }

        if (lockStatus == LockStatus.WRITE) {
            LOG.debug("Released writeLock for '{}'", lockIdentifier);
            lock.writeLock().unlock();
        } else {
            LOG.debug("Released readLock for '{}'", lockIdentifier);
            readLock.unlock();
        }
        ResourceLock.releaseLocker(lockIdentifier);
    }
}

From source file:org.apache.hadoop.hbase.master.AssignmentManager.java

/**
 * Use care with forceNewPlan. It could cause double assignment.
 *//*from  w ww .j  a va  2 s .  c  o m*/
public void assign(HRegionInfo region, boolean setOfflineInZK, boolean forceNewPlan) {
    if (isDisabledorDisablingRegionInRIT(region)) {
        return;
    }
    if (this.serverManager.isClusterShutdown()) {
        LOG.info("Cluster shutdown is set; skipping assign of " + region.getRegionNameAsString());
        return;
    }
    String encodedName = region.getEncodedName();
    Lock lock = locker.acquireLock(encodedName);
    try {
        RegionState state = forceRegionStateToOffline(region, forceNewPlan);
        if (state != null) {
            if (regionStates.wasRegionOnDeadServer(encodedName)) {
                LOG.info("Skip assigning " + region.getRegionNameAsString() + ", it's host "
                        + regionStates.getLastRegionServerOfRegion(encodedName)
                        + " is dead but not processed yet");
                return;
            }
            assign(state, setOfflineInZK, forceNewPlan);
        }
    } finally {
        lock.unlock();
    }
}

From source file:it.isislab.dmason.util.SystemManagement.Master.thrower.DMasonMaster.java

public void nextTest() {
    // TODO Auto-generated method stub
    System.out.println("unlock");

    batchExec.setCanStartAnother(true);//from ww w . j  a  v a  2s.c  om

    Lock batchLock = batchExec.getLock();
    batchLock.lock();
    {
        batchExec.getIsResetted().signalAll();
    }
    batchLock.unlock();
}

From source file:org.apache.hadoop.hbase.master.procedure.ServerCrashProcedure.java

/**
 * Figure out what we need to assign. Should be idempotent.
 * @param env/* ww w.  j a  v  a 2s . co  m*/
 * @return List of calculated regions to assign; may be empty or null.
 * @throws IOException
 */
private List<HRegionInfo> calcRegionsToAssign(final MasterProcedureEnv env) throws IOException {
    AssignmentManager am = env.getMasterServices().getAssignmentManager();
    List<HRegionInfo> regionsToAssignAggregator = new ArrayList<HRegionInfo>();
    int replicaCount = env.getMasterConfiguration().getInt(HConstants.META_REPLICAS_NUM,
            HConstants.DEFAULT_META_REPLICA_NUM);
    for (int i = 1; i < replicaCount; i++) {
        HRegionInfo metaHri = RegionReplicaUtil.getRegionInfoForReplica(HRegionInfo.FIRST_META_REGIONINFO, i);
        if (am.isCarryingMetaReplica(this.serverName, metaHri)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Reassigning meta replica" + metaHri + " that was on " + this.serverName);
            }
            regionsToAssignAggregator.add(metaHri);
        }
    }
    // Clean out anything in regions in transition.
    List<HRegionInfo> regionsInTransition = am.cleanOutCrashedServerReferences(serverName);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Reassigning " + size(this.regionsOnCrashedServer) + " region(s) that "
                + (serverName == null ? "null" : serverName) + " was carrying (and "
                + regionsInTransition.size() + " regions(s) that were opening on this server)");
    }
    regionsToAssignAggregator.addAll(regionsInTransition);

    // Iterate regions that were on this server and figure which of these we need to reassign
    if (this.regionsOnCrashedServer != null && !this.regionsOnCrashedServer.isEmpty()) {
        RegionStates regionStates = am.getRegionStates();
        for (HRegionInfo hri : this.regionsOnCrashedServer) {
            if (regionsInTransition.contains(hri))
                continue;
            String encodedName = hri.getEncodedName();
            Lock lock = am.acquireRegionLock(encodedName);
            try {
                RegionState rit = regionStates.getRegionTransitionState(hri);
                if (processDeadRegion(hri, am)) {
                    ServerName addressFromAM = regionStates.getRegionServerOfRegion(hri);
                    if (addressFromAM != null && !addressFromAM.equals(this.serverName)) {
                        // If this region is in transition on the dead server, it must be
                        // opening or pending_open, which should have been covered by
                        // AM#cleanOutCrashedServerReferences
                        LOG.info("Skip assigning " + hri.getRegionNameAsString() + " because opened on "
                                + addressFromAM.getServerName());
                        continue;
                    }
                    if (rit != null) {
                        if (rit.getServerName() != null && !rit.isOnServer(this.serverName)) {
                            // Skip regions that are in transition on other server
                            LOG.info("Skip assigning region in transition on other server" + rit);
                            continue;
                        }
                        LOG.info("Reassigning region " + rit + " and clearing zknode if exists");
                        regionStates.updateRegionState(hri, RegionState.State.OFFLINE);
                    } else if (regionStates.isRegionInState(hri, RegionState.State.SPLITTING_NEW,
                            RegionState.State.MERGING_NEW)) {
                        regionStates.updateRegionState(hri, RegionState.State.OFFLINE);
                    }
                    regionsToAssignAggregator.add(hri);
                    // TODO: The below else if is different in branch-1 from master branch.
                } else if (rit != null) {
                    if ((rit.isClosing() || rit.isFailedClose() || rit.isOffline()) && am.getTableStateManager()
                            .isTableState(hri.getTable(), TableState.State.DISABLED, TableState.State.DISABLING)
                            || am.getReplicasToClose().contains(hri)) {
                        // If the table was partially disabled and the RS went down, we should clear the
                        // RIT and remove the node for the region.
                        // The rit that we use may be stale in case the table was in DISABLING state
                        // but though we did assign we will not be clearing the znode in CLOSING state.
                        // Doing this will have no harm. See HBASE-5927
                        regionStates.updateRegionState(hri, RegionState.State.OFFLINE);
                        am.offlineDisabledRegion(hri);
                    } else {
                        LOG.warn("THIS SHOULD NOT HAPPEN: unexpected region in transition " + rit
                                + " not to be assigned by SSH of server " + serverName);
                    }
                }
            } finally {
                lock.unlock();
            }
        }
    }
    return regionsToAssignAggregator;
}

From source file:org.apache.hadoop.hbase.master.handler.ServerShutdownHandler.java

@Override
public void process() throws IOException {
    boolean hasLogReplayWork = false;
    final ServerName serverName = this.serverName;
    try {//from   w w  w. j ava 2s.  co m

        // We don't want worker thread in the MetaServerShutdownHandler
        // executor pool to block by waiting availability of hbase:meta
        // Otherwise, it could run into the following issue:
        // 1. The current MetaServerShutdownHandler instance For RS1 waits for the hbase:meta
        //    to come online.
        // 2. The newly assigned hbase:meta region server RS2 was shutdown right after
        //    it opens the hbase:meta region. So the MetaServerShutdownHandler
        //    instance For RS1 will still be blocked.
        // 3. The new instance of MetaServerShutdownHandler for RS2 is queued.
        // 4. The newly assigned hbase:meta region server RS3 was shutdown right after
        //    it opens the hbase:meta region. So the MetaServerShutdownHandler
        //    instance For RS1 and RS2 will still be blocked.
        // 5. The new instance of MetaServerShutdownHandler for RS3 is queued.
        // 6. Repeat until we run out of MetaServerShutdownHandler worker threads
        // The solution here is to resubmit a ServerShutdownHandler request to process
        // user regions on that server so that MetaServerShutdownHandler
        // executor pool is always available.
        //
        // If AssignmentManager hasn't finished rebuilding user regions,
        // we are not ready to assign dead regions either. So we re-queue up
        // the dead server for further processing too.
        AssignmentManager am = services.getAssignmentManager();
        if (isCarryingMeta() // hbase:meta
                || !am.isFailoverCleanupDone()) {
            this.services.getServerManager().processDeadServer(serverName, this.shouldSplitHlog);
            return;
        }

        // Wait on meta to come online; we need it to progress.
        // TODO: Best way to hold strictly here?  We should build this retry logic
        // into the MetaReader operations themselves.
        // TODO: Is the reading of hbase:meta necessary when the Master has state of
        // cluster in its head?  It should be possible to do without reading hbase:meta
        // in all but one case. On split, the RS updates the hbase:meta
        // table and THEN informs the master of the split via zk nodes in
        // 'unassigned' dir.  Currently the RS puts ephemeral nodes into zk so if
        // the regionserver dies, these nodes do not stick around and this server
        // shutdown processing does fixup (see the fixupDaughters method below).
        // If we wanted to skip the hbase:meta scan, we'd have to change at least the
        // final SPLIT message to be permanent in zk so in here we'd know a SPLIT
        // completed (zk is updated after edits to hbase:meta have gone in).  See
        // {@link SplitTransaction}.  We'd also have to be figure another way for
        // doing the below hbase:meta daughters fixup.
        NavigableMap<HRegionInfo, Result> hris = null;
        while (!this.server.isStopped()) {
            try {
                this.server.getCatalogTracker().waitForMeta();
                // Skip getting user regions if the server is stopped.
                if (!this.server.isStopped()) {
                    hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(), this.serverName);
                }
                break;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw (InterruptedIOException) new InterruptedIOException().initCause(e);
            } catch (IOException ioe) {
                LOG.info("Received exception accessing hbase:meta during server shutdown of " + serverName
                        + ", retrying hbase:meta read", ioe);
            }
        }
        if (this.server.isStopped()) {
            throw new IOException("Server is stopped");
        }

        try {
            if (this.shouldSplitHlog) {
                LOG.info("Splitting logs for " + serverName + " before assignment.");
                if (this.distributedLogReplay) {
                    LOG.info("Mark regions in recovery before assignment.");
                    Set<ServerName> serverNames = new HashSet<ServerName>();
                    serverNames.add(serverName);
                    this.services.getMasterFileSystem().prepareLogReplay(serverNames);
                } else {
                    this.services.getMasterFileSystem().splitLog(serverName);
                }
                am.getRegionStates().logSplit(serverName);
            } else {
                LOG.info("Skipping log splitting for " + serverName);
            }
        } catch (IOException ioe) {
            resubmit(serverName, ioe);
        }

        // Clean out anything in regions in transition.  Being conservative and
        // doing after log splitting.  Could do some states before -- OPENING?
        // OFFLINE? -- and then others after like CLOSING that depend on log
        // splitting.
        List<HRegionInfo> regionsInTransition = am.processServerShutdown(serverName);
        LOG.info("Reassigning " + ((hris == null) ? 0 : hris.size()) + " region(s) that "
                + (serverName == null ? "null" : serverName) + " was carrying (and "
                + regionsInTransition.size() + " regions(s) that were opening on this server)");

        List<HRegionInfo> toAssignRegions = new ArrayList<HRegionInfo>();
        toAssignRegions.addAll(regionsInTransition);

        // Iterate regions that were on this server and assign them
        if (hris != null) {
            RegionStates regionStates = am.getRegionStates();
            for (Map.Entry<HRegionInfo, Result> e : hris.entrySet()) {
                HRegionInfo hri = e.getKey();
                if (regionsInTransition.contains(hri)) {
                    continue;
                }
                String encodedName = hri.getEncodedName();
                Lock lock = am.acquireRegionLock(encodedName);
                try {
                    RegionState rit = regionStates.getRegionTransitionState(hri);
                    if (processDeadRegion(hri, e.getValue(), am, server.getCatalogTracker())) {
                        ServerName addressFromAM = regionStates.getRegionServerOfRegion(hri);
                        if (addressFromAM != null && !addressFromAM.equals(this.serverName)) {
                            // If this region is in transition on the dead server, it must be
                            // opening or pending_open, which should have been covered by AM#processServerShutdown
                            LOG.info("Skip assigning region " + hri.getRegionNameAsString()
                                    + " because it has been opened in " + addressFromAM.getServerName());
                            continue;
                        }
                        if (rit != null) {
                            if (rit.getServerName() != null && !rit.isOnServer(serverName)) {
                                // Skip regions that are in transition on other server
                                LOG.info("Skip assigning region in transition on other server" + rit);
                                continue;
                            }
                            try {
                                //clean zk node
                                LOG.info("Reassigning region with rs = " + rit
                                        + " and deleting zk node if exists");
                                ZKAssign.deleteNodeFailSilent(services.getZooKeeper(), hri);
                                regionStates.updateRegionState(hri, State.OFFLINE);
                            } catch (KeeperException ke) {
                                this.server.abort("Unexpected ZK exception deleting unassigned node " + hri,
                                        ke);
                                return;
                            }
                        } else if (regionStates.isRegionInState(hri, State.SPLITTING_NEW, State.MERGING_NEW)) {
                            regionStates.regionOffline(hri);
                        }
                        toAssignRegions.add(hri);
                    } else if (rit != null) {
                        if (rit.isPendingCloseOrClosing() && am.getTableStateManager().isTableState(
                                hri.getTable(), ZooKeeperProtos.Table.State.DISABLED,
                                ZooKeeperProtos.Table.State.DISABLING)) {
                            // If the table was partially disabled and the RS went down, we should clear the RIT
                            // and remove the node for the region.
                            // The rit that we use may be stale in case the table was in DISABLING state
                            // but though we did assign we will not be clearing the znode in CLOSING state.
                            // Doing this will have no harm. See HBASE-5927
                            regionStates.updateRegionState(hri, State.OFFLINE);
                            am.deleteClosingOrClosedNode(hri, rit.getServerName());
                            am.offlineDisabledRegion(hri);
                        } else {
                            LOG.warn("THIS SHOULD NOT HAPPEN: unexpected region in transition " + rit
                                    + " not to be assigned by SSH of server " + serverName);
                        }
                    }
                } finally {
                    lock.unlock();
                }
            }
        }

        try {
            am.assign(toAssignRegions);
        } catch (InterruptedException ie) {
            LOG.error("Caught " + ie + " during round-robin assignment");
            throw (InterruptedIOException) new InterruptedIOException().initCause(ie);
        }

        if (this.shouldSplitHlog && this.distributedLogReplay) {
            // wait for region assignment completes
            for (HRegionInfo hri : toAssignRegions) {
                try {
                    if (!am.waitOnRegionToClearRegionsInTransition(hri, regionAssignmentWaitTimeout)) {
                        // Wait here is to avoid log replay hits current dead server and incur a RPC timeout
                        // when replay happens before region assignment completes.
                        LOG.warn("Region " + hri.getEncodedName() + " didn't complete assignment in time");
                    }
                } catch (InterruptedException ie) {
                    throw new InterruptedIOException(
                            "Caught " + ie + " during waitOnRegionToClearRegionsInTransition");
                }
            }
            // submit logReplay work
            this.services.getExecutorService().submit(
                    new LogReplayHandler(this.server, this.services, this.deadServers, this.serverName));
            hasLogReplayWork = true;
        }
    } finally {
        this.deadServers.finish(serverName);
    }

    if (!hasLogReplayWork) {
        LOG.info("Finished processing of shutdown of " + serverName);
    }
}

From source file:org.rhq.core.pc.inventory.InventoryManager.java

@NotNull
// TODO (ips): Perhaps refactor this so that it shares code with AvailabilityExecutor.checkInventory().
public Availability getCurrentAvailability(Resource resource) {
    AvailabilityType availType = null; // i.e. UNKNOWN;
    ResourceContainer resourceContainer = getResourceContainer(resource);
    if (resourceContainer != null) {
        if (resourceContainer.getResourceComponentState() == ResourceComponentState.STARTED) {
            AvailabilityFacet resourceComponent;
            Lock lock = resourceContainer.getReadFacetLock();
            if (lock.tryLock()) {
                // We have acquired the lock.
                try {
                    ResourceCategory resourceCategory = resource.getResourceType().getCategory();
                    // Give the call to getAvailability() a bit more time if the Resource is a server.
                    long componentTimeout = (resourceCategory == ResourceCategory.SERVER) ? 10000 : 5000;
                    // We already possess the lock, so tell the proxy not to do any locking of its own.
                    resourceComponent = resourceContainer.createResourceComponentProxy(AvailabilityFacet.class,
                            FacetLockType.NONE, componentTimeout, true, true);
                    availType = resourceComponent.getAvailability();
                } catch (PluginContainerException e) {
                    log.error("Failed to retrieve ResourceComponent for " + resource + ".", e);
                } catch (RuntimeException e) {
                    log.error("Call to getAvailability() on ResourceComponent for " + resource + " failed.", e);
                    availType = AvailabilityType.DOWN;
                } finally {
                    lock.unlock();
                }//from w w  w . j a  v a  2 s  . c  o m
            } else {
                // Some other thread possesses the lock - return the last-collected availability for the Resource if
                // there is one.
                if (resourceContainer.getAvailability() != null)
                    return resourceContainer.getAvailability();
            }
        }
    } else {
        log.error("No ResourceContainer exists for " + resource + ".");
    }
    return new Availability(resource, availType);
}

From source file:org.jasig.portal.portlet.container.services.PortletPreferencesServiceImpl.java

@Transactional
@Override//  www .  j a  va2 s.  c  om
public void store(PortletWindow plutoPortletWindow, PortletRequest portletRequest,
        Map<String, PortletPreference> newPreferences) throws PortletContainerException {
    final HttpServletRequest httpServletRequest = this.portalRequestUtils.getPortletHttpRequest(portletRequest);

    //Determine if the user is a guest
    final boolean isGuest = isGuestUser(portletRequest);

    //If this is a guest and no prefs are being stored just return as the rest of the method is not needed for this case
    if (isGuest && !(this.isStoreInEntity(portletRequest) || this.isStoreInMemory(portletRequest))) {
        return;
    }

    final IPortletWindow portletWindow = this.portletWindowRegistry.convertPortletWindow(httpServletRequest,
            plutoPortletWindow);
    IPortletEntity portletEntity = portletWindow.getPortletEntity();
    final IPortletEntityId portletEntityId = portletEntity.getPortletEntityId();
    final IPortletDefinition portletDefinition = portletEntity.getPortletDefinition();
    final PortletDefinition portletDescriptor = this.portletDefinitionRegistry
            .getParentPortletDescriptor(portletDefinition.getPortletDefinitionId());

    //Is this CONFIG mode
    final boolean configMode = IPortletRenderer.CONFIG.equals(portletWindow.getPortletMode());

    //Get Map of descriptor and definition preferences to check new preferences against
    final Map<String, PortletPreference> basePreferences = new HashMap<String, PortletPreference>();

    //Add deploy preferences
    final List<IPortletPreference> descriptorPreferencesList = this.getDescriptorPreferences(portletDescriptor);
    this.addPreferencesToMap(descriptorPreferencesList, basePreferences, configMode);

    final Lock prefLock;
    if (configMode) {
        //In config mode we don't worry about locking
        prefLock = NoopLock.INSTANCE;
    } else {
        prefLock = this.portletEntityRegistry.getPortletEntityLock(httpServletRequest, portletEntityId);
    }

    //Do a tryLock firsrt so that we can warn about concurrent preference modification if it fails
    boolean locked = prefLock.tryLock();
    try {
        if (!locked) {
            logger.warn("Concurrent portlet preferences modification by: " + portletDefinition.getFName() + " "
                    + "This has the potential for changes to preferences to be lost. "
                    + "This portlet should be modified to synchronize its preference modifications appropriately",
                    new Throwable());

            prefLock.lock();
            locked = true;

            //Refresh the portlet entity that may have been changed by the thread we were blocked by
            if (!configMode) {
                portletEntity = this.portletEntityRegistry.getPortletEntity(httpServletRequest,
                        portletEntityId);
            }
        }

        //Add definition preferences if not config mode
        if (!configMode) {
            final List<IPortletPreference> definitionPreferencesList = portletDefinition
                    .getPortletPreferences();
            this.addPreferencesToMap(definitionPreferencesList, basePreferences, false);
        }

        final List<IPortletPreference> preferencesList = new ArrayList<IPortletPreference>(
                newPreferences.size());

        for (final PortletPreference internalPreference : newPreferences.values()) {
            //Ignore preferences with null names
            final String name = internalPreference.getName();
            if (name == null) {
                throw new IllegalArgumentException("PortletPreference name cannot be null");
            }

            //Convert to a uPortal preference class to ensure quality check and persistence works
            final IPortletPreference preference = new PortletPreferenceImpl(internalPreference);

            //If the preference exactly equals a descriptor or definition preference ignore it
            final PortletPreference basePreference = basePreferences.get(name);
            if (preference.equals(basePreference)) {
                continue;
            }

            //New preference, add it to the list
            preferencesList.add(preference);
        }

        //If in config mode store the preferences on the definition
        if (configMode) {
            portletDefinition.setPortletPreferences(preferencesList);
            this.portletDefinitionRegistry.updatePortletDefinition(portletDefinition);
        }
        //If not a guest or if guest prefs are shared store them on the entity
        else if (this.isStoreInEntity(portletRequest)) {
            //Update the portlet entity with the new preferences
            portletEntity.setPortletPreferences(preferencesList);
            this.portletEntityRegistry.storePortletEntity(httpServletRequest, portletEntity);
        }
        //Must be a guest and share must be off so store the prefs on the session
        else {
            //Store memory preferences
            this.storeSessionPreferences(portletEntityId, httpServletRequest, preferencesList);
        }
    } finally {
        //check if locked, needed due to slighly more complex logic around the tryLock and logging
        if (locked) {
            prefLock.unlock();
        }
    }
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * Updates the task stopping it and rescheduling it
 * @param task the task to update//from   w ww  . j a va2  s . c  om
 */
public void updateScheduledTask(ScheduledTaskWrapper task) {
    if (task == null) {
        if (log.isTraceEnabled()) {
            log.trace("Trying to update a null task. Request rejected");
        }
        return;
    }
    if (log.isInfoEnabled()) {
        log.info("Updating task '" + task + "'. The task will be cancelled and " + "then re-scheduled");
    }
    //
    // Locking the lock for this task so no other thread can handle it avoiding
    // conflict (what happens if a thread is removing it an another threead is
    // updating it ?)
    //
    Lock handlingTaskLock = getHandlingTaskLock(task.getId());
    handlingTaskLock.lock();
    try {
        ScheduledFuture scheduledFuture = null;
        ScheduledTaskWrapper oldScheduledTask = null;

        synchronized (scheduledFutures) {
            scheduledFuture = (ScheduledFuture) scheduledFutures.get(task);
            oldScheduledTask = (ScheduledTaskWrapper) scheduledFutures.getKey(scheduledFuture);
        }

        boolean cancelled = false;
        if (scheduledFuture != null) {
            cancelled = scheduledFuture.isCancelled();
            if (!cancelled) {
                cancelled = scheduledFuture.cancel(true); // if we can, we stop its
                                                          // execution. Remember that
                                                          // cancel means cancel its
                                                          // scheduled execution and
                                                          // not just the running one
                if (cancelled) {
                    if (log.isTraceEnabled()) {
                        log.trace("Task '" + task.getId() + "' cancelled successfully");
                    }
                } else {
                    if (log.isTraceEnabled()) {
                        log.trace("Task '" + task.getId() + "' not cancelled for unknown reasons."
                                + "Is it already cancelled ? "
                                + ((scheduledFuture.isCancelled() ? "YES" : "NO")));
                    }
                }

            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Task '" + task.getId() + "' has been already cancelled");
                }
            }
            if (!ScheduledTaskWrapper.State.SHUTDOWN.equals(oldScheduledTask.getState())) {
                if (log.isTraceEnabled()) {
                    log.trace("Shutting down task '" + task.getId() + "'");
                }
                try {
                    oldScheduledTask.shutdown();
                } catch (TaskException ex) {
                    log.error("Error shutting down scheduled task '" + oldScheduledTask + "'", ex);
                }
                oldScheduledTask.setState(ScheduledTaskWrapper.State.SHUTDOWN);
            }

            synchronized (scheduledFutures) {
                //
                // Any time we remove the scheduledTask from scheduledFutures,
                // we try to remove the scheduledFuture from the queue. This
                // is not really needed because after a while this is performed
                // automatically but in this way we keep scheduledFutures and
                // the queue in sync
                //
                if (scheduledFuture instanceof Runnable) {
                    super.remove((Runnable) scheduledFuture);
                }
                scheduledFutures.remove(oldScheduledTask);
            }

        } else {
            if (log.isTraceEnabled()) {
                log.trace("Task '" + task + "' seems not scheduled");
            }
        }
        scheduleTask(task, 0);
    } finally {
        handlingTaskLock.unlock();
    }
}