Example usage for java.util.concurrent.locks ReentrantLock ReentrantLock

List of usage examples for java.util.concurrent.locks ReentrantLock ReentrantLock

Introduction

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

Prototype

public ReentrantLock() 

Source Link

Document

Creates an instance of ReentrantLock .

Usage

From source file:org.wso2.carbon.appmgt.gateway.internal.TenantCreateGatewayObserver.java

/**
 * Create synapse sequence.//w  ww  . j  a  v a2s. co  m
 *
 * @param configurationContext {@link ConfigurationContext} object
 */
public void createdConfigurationContext(ConfigurationContext configurationContext) {
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        // First check which configuration should be active.
        org.wso2.carbon.registry.core.Registry registry = (org.wso2.carbon.registry.core.Registry) PrivilegedCarbonContext
                .getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);

        AxisConfiguration axisConfig = configurationContext.getAxisConfiguration();

        // Initialize the lock.
        Lock lock = new ReentrantLock();
        axisConfig.addParameter("synapse.config.lock", lock);

        // Creates the synapse configuration directory hierarchy if not exists.
        // Useful at the initial tenant creation.
        File tenantAxis2Repo = new File(configurationContext.getAxisConfiguration().getRepository().getFile());
        File synapseConfigsDir = new File(tenantAxis2Repo, "synapse-configs");
        if (!synapseConfigsDir.exists()) {
            if (!synapseConfigsDir.mkdir()) {
                log.fatal("Couldn't create the synapse-config root on the file system for the tenant domain : "
                        + tenantDomain);
                return;
            }
        }

        String synapseConfigsDirLocation = synapseConfigsDir.getAbsolutePath();
        // Set the required configuration parameters to initialize ESB.
        axisConfig.addParameter(SynapseConstants.Axis2Param.SYNAPSE_CONFIG_LOCATION, synapseConfigsDirLocation);

        // Init multiple configuration tracker.
        ConfigurationManager configurationManager = new ConfigurationManager((UserRegistry) registry,
                configurationContext);
        configurationManager.init();

        File synapseConfigDir = new File(synapseConfigsDir,
                configurationManager.getTracker().getCurrentConfigurationName());
        File buildSequenceFile = new File(synapseConfigsDir + File.separator
                + configurationManager.getTracker().getCurrentConfigurationName() + File.separator
                + MultiXMLConfigurationBuilder.SEQUENCES_DIR + File.separator + buildSequenceName + ".xml");

        //Here we will check build sequence exist in synapse artifact. If it is not available , we will create
        //sequence synapse configurations by using resource artifacts.
        if (!buildSequenceFile.exists()) {
            createTenantSynapseConfigHierarchy(synapseConfigDir, tenantDomain);
        }
    } catch (AxisFault e) {
        log.error("Failed to create tenant's synapse sequences for tenant : " + tenantDomain);
    } catch (ConfigurationInitilizerException e) {
        log.error("Failed to initialize configuration. ");
    }

    try {
        AppManagerUtil.loadTenantAPIPolicy(tenantDomain, tenantId);
    } catch (AppManagementException e) {
        log.error("Failed to load tiers.xml to tenant's registry.");
    }
}

From source file:SynchBankTest.java

/**
 * Constructs the bank./*from  w  w w .j  a v  a2 s.c  o m*/
 * 
 * @param n
 *          the number of accounts
 * @param initialBalance
 *          the initial balance for each account
 */
public Bank(int n, double initialBalance) {
    accounts = new double[n];
    for (int i = 0; i < accounts.length; i++)
        accounts[i] = initialBalance;
    bankLock = new ReentrantLock();
    sufficientFunds = bankLock.newCondition();
}

From source file:com.gigaspaces.simpledao.dao.AbstractBaseDAO.java

private T[] runQuery(String query, int count, Object[] parameters, Actor<T> actor) {
    if (query.trim().toLowerCase().startsWith("where")) {
        query = query.trim().substring(6);
    }/*from   w  w  w .  j a v  a 2 s . c  o  m*/
    if (!queries.containsKey(query)) {
        SQLQuery<T> queryObject = new SQLQuery<T>(persistentClass, query);
        queries.put(query, new Pair<Lock, SQLQuery<T>>(new ReentrantLock(), queryObject));
    }
    Pair<Lock, SQLQuery<T>> pair = queries.get(query);
    pair.getK().lock();
    try {
        pair.getV().setParameters(parameters);
        return actor.execute(pair.getV(), count);
    } finally {
        pair.getK().unlock();
    }
}

From source file:org.broadleafcommerce.core.web.order.SessionOrderLockManager.java

protected ReentrantLock getSessionLock() {
    if (!isActive()) {
        throw new IllegalStateException(
                "This is currently a sessionless environment and session cannot be used "
                        + "to obtain a lock. Consider using a different implementation of OrderLockManager.");
    }//from   ww w .  j  a va  2  s. co  m

    HttpSession session = getRequest().getSession();
    ReentrantLock lock = SESSION_LOCKS.get(session.getId());

    if (lock == null) {
        // There was no session lock object. We'll need to create one. To do this, we have to synchronize the
        // creation globally, so that two threads don't create the session lock at the same time.
        synchronized (LOCK) {
            lock = SESSION_LOCKS.get(session.getId());
            if (lock == null) {
                lock = new ReentrantLock();
                SESSION_LOCKS.put(session.getId(), lock);
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new lock object: " + lock.toString());
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Returning previously created lock object: " + lock.toString());
        }
    }

    return lock;
}

From source file:net.ymate.platform.webmvc.support.WebCacheProcessor.java

private ReentrantLock __doGetCacheLocker(String cacheKey) {
    ReentrantLock _locker = __LOCK_MAP.get(cacheKey);
    if (_locker == null) {
        _locker = new ReentrantLock();
        ReentrantLock _previous = __LOCK_MAP.putIfAbsent(cacheKey, _locker);
        if (_previous != null) {
            _locker = _previous;//  www .  ja va 2 s .co m
        }
    }
    return _locker;
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java

/**
 * Constructs a UPNP-IGD controller.//w  w  w .java 2s .  co m
 * @param selfAddress address of this machine.
 * @param controlUrl control URL
 * @param serviceType service type
 * @param listener event listener
 * @throws NullPointerException if any argument other than {@code listener} is {@code null}
 */
public UpnpIgdController(InetAddress selfAddress, URI controlUrl, String serviceType,
        final UpnpIgdControllerListener listener) {
    Validate.notNull(selfAddress);
    Validate.notNull(controlUrl);
    Validate.notNull(serviceType);
    this.selfAddress = selfAddress;
    this.controlUrl = controlUrl;
    this.serviceType = serviceType;

    activePortsLock = new ReentrantLock();
    activePorts = new HashMap<>();
    scheduledPortTester = Executors.newSingleThreadScheduledExecutor(
            new BasicThreadFactory.Builder().daemon(false).namingPattern("upnp-port-tester").build());

    if (listener != null) {
        scheduledPortTester.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                // get random port mapping
                List<PortMappingInfo> ports;
                activePortsLock.lock();
                try {
                    ports = new ArrayList<>(activePorts.values());
                } finally {
                    activePortsLock.unlock();
                }

                if (ports.isEmpty()) {
                    return;
                }

                Random random = new Random();
                PortMappingInfo oldPmi = ports.get(random.nextInt(ports.size()));

                // check to see if its still active
                boolean mappingFailed;
                try {
                    PortMappingInfo newPmi = getMappingDetails(oldPmi.getExternalPort(), oldPmi.getPortType());

                    mappingFailed = !newPmi.getInternalClient().equals(UpnpIgdController.this.selfAddress)
                            || newPmi.getInternalPort() != oldPmi.getInternalPort()
                            || newPmi.getPortType() != oldPmi.getPortType();
                } catch (Exception e) {
                    mappingFailed = true;
                }

                // if it isn't, check to see that the user didn't remove it while we were testing it and notify
                if (mappingFailed) {
                    activePortsLock.lock();
                    try {
                        PortMappingInfo testPmi = activePorts.get(oldPmi.getExternalPort());
                        if (testPmi == null) {
                            return;
                        }

                        if (testPmi.getInternalClient().equals(UpnpIgdController.this.selfAddress)
                                && testPmi.getInternalPort() == oldPmi.getInternalPort()
                                && testPmi.getPortType() == oldPmi.getPortType()) {
                            activePorts.remove(oldPmi.externalPort);
                            listener.mappingExpired(oldPmi);
                        }
                    } finally {
                        activePortsLock.unlock();
                    }
                }
            }
        }, RANDOM_PORT_TEST_SLEEP, RANDOM_PORT_TEST_SLEEP, TimeUnit.SECONDS);
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.DiskBalancer.java

/**
 * Constructs a Disk Balancer object. This object takes care of reading a
 * NodePlan and executing it against a set of volumes.
 *
 * @param dataNodeUUID - Data node UUID//from  ww w  .  j  a va 2  s.  c  o m
 * @param conf         - Hdfs Config
 * @param blockMover   - Object that supports moving blocks.
 */
public DiskBalancer(String dataNodeUUID, Configuration conf, BlockMover blockMover) {
    this.currentResult = Result.NO_PLAN;
    this.blockMover = blockMover;
    this.dataset = this.blockMover.getDataset();
    this.dataNodeUUID = dataNodeUUID;
    scheduler = Executors.newSingleThreadExecutor();
    lock = new ReentrantLock();
    workMap = new ConcurrentHashMap<>();
    this.planID = ""; // to keep protobuf happy.
    this.planFile = ""; // to keep protobuf happy.
    this.isDiskBalancerEnabled = conf.getBoolean(DFSConfigKeys.DFS_DISK_BALANCER_ENABLED,
            DFSConfigKeys.DFS_DISK_BALANCER_ENABLED_DEFAULT);
    this.bandwidth = conf.getInt(DFSConfigKeys.DFS_DISK_BALANCER_MAX_DISK_THROUGHPUT,
            DFSConfigKeys.DFS_DISK_BALANCER_MAX_DISK_THROUGHPUT_DEFAULT);
}

From source file:org.wso2.carbon.appmgt.impl.observers.TenantServiceCreator.java

public void createdConfigurationContext(ConfigurationContext configurationContext) {
    /*String tenantDomain =
        PrivilegedCarbonContext.getCurrentContext(configurationContext).getTenantDomain();
    int tenantId =  PrivilegedCarbonContext.getCurrentContext(configurationContext).getTenantId();*/
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {//  w w  w .  ja va 2 s  . co  m
        // first check which configuration should be active
        org.wso2.carbon.registry.core.Registry registry = (org.wso2.carbon.registry.core.Registry) PrivilegedCarbonContext
                .getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);

        AxisConfiguration axisConfig = configurationContext.getAxisConfiguration();

        // initialize the lock
        Lock lock = new ReentrantLock();
        axisConfig.addParameter("synapse.config.lock", lock);

        // creates the synapse configuration directory hierarchy if not exists
        // useful at the initial tenant creation
        File tenantAxis2Repo = new File(configurationContext.getAxisConfiguration().getRepository().getFile());
        File synapseConfigsDir = new File(tenantAxis2Repo, "synapse-configs");
        if (!synapseConfigsDir.exists()) {
            if (!synapseConfigsDir.mkdir()) {
                log.fatal("Couldn't create the synapse-config root on the file system "
                        + "for the tenant domain : " + tenantDomain);
                return;
            }
        }

        String synapseConfigsDirLocation = synapseConfigsDir.getAbsolutePath();
        // set the required configuration parameters to initialize the ESB
        axisConfig.addParameter(SynapseConstants.Axis2Param.SYNAPSE_CONFIG_LOCATION, synapseConfigsDirLocation);

        // init the multiple configuration tracker
        ConfigurationManager manger = new ConfigurationManager((UserRegistry) registry, configurationContext);
        manger.init();

        File synapseConfigDir = new File(synapseConfigsDir, manger.getTracker().getCurrentConfigurationName());
        File buildSequenceFile = new File(
                synapseConfigsDir + "/" + manger.getTracker().getCurrentConfigurationName() + "/"
                        + MultiXMLConfigurationBuilder.SEQUENCES_DIR + "/" + buildSequenceName + ".xml");
        //Here we will check build sequence exist in synapse artifact. If it is not available we will create
        //sequence synapse configurations by using resource artifacts
        if (!buildSequenceFile.exists()) {
            createTenantSynapseConfigHierarchy(synapseConfigDir, tenantDomain);
        }
    } catch (Exception e) {
        log.error("Failed to create Tenant's synapse sequences.");
    }

    try {
        AppManagerUtil.loadTenantAPIPolicy(tenantDomain, tenantId);
    } catch (Exception e) {
        log.error("Failed to load tiers.xml to tenant's registry");
    }

    try {
        //load workflow-extension configuration to the registry
        AppManagerUtil.loadTenantWorkFlowExtensions(tenantId);
    } catch (Exception e) {
        log.error("Failed to load workflow-extension.xml to tenant " + tenantDomain + "'s registry");
    }

    try {
        //Add the creator & publisher roles if not exists
        //Apply permissons to appmgt collection for creator role
        UserRealm realm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();

        Permission[] creatorPermissions = new Permission[] {
                new Permission(AppMConstants.Permissions.LOGIN, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.WEB_APP_CREATE, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.WEB_APP_DELETE, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.WEB_APP_UPDATE, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.DOCUMENT_ADD, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.DOCUMENT_DELETE, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.DOCUMENT_EDIT, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.MOBILE_APP_CREATE, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.MOBILE_APP_DELETE, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.MOBILE_APP_UPDATE, UserMgtConstants.EXECUTE_ACTION) };

        AppManagerUtil.addNewRole(AppMConstants.CREATOR_ROLE, creatorPermissions, realm);

        Permission[] publisherPermissions = new Permission[] {
                new Permission(AppMConstants.Permissions.LOGIN, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.WEB_APP_PUBLISH, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.VIEW_STATS, UserMgtConstants.EXECUTE_ACTION),
                new Permission(AppMConstants.Permissions.MOBILE_APP_PUBLISH, UserMgtConstants.EXECUTE_ACTION) };

        AppManagerUtil.addNewRole(AppMConstants.PUBLISHER_ROLE, publisherPermissions, realm);
        //            AppManagerUtil.applyRolePermissionToCollection(AppMConstants.CREATOR_ROLE, realm);

        //Add the store-admin role
        Permission[] storeAdminPermissions = new Permission[] {
                new Permission(AppMConstants.Permissions.LOGIN, UserMgtConstants.EXECUTE_ACTION) };
        AppManagerUtil.addNewRole(AppMConstants.STORE_ADMIN_ROLE, storeAdminPermissions, realm);
    } catch (Exception e) {
        log.error("Failed to add permissions of appmgt/application data collection for creator role.");
    }

    try {
        AppManagerUtil.writeDefinedSequencesToTenantRegistry(tenantId);
    } catch (Exception e) {
        log.error("Failed to write defined sequences to tenant " + tenantDomain + "'s registry");
    }
}

From source file:org.apache.synapse.debug.SynapseDebugManager.java

protected SynapseDebugManager() {
    mediationFlowLock = new ReentrantLock();
    mediationFlowSem = new Semaphore(0);
    addedPropertyValuesMap = new HashMap<MessageContext, Map<String, Set<String>>>();
}

From source file:org.onosproject.drivers.bmv2.Bmv2FlowRuleProgrammable.java

@Override
public Collection<FlowEntry> getFlowEntries() {

    if (!init()) {
        return Collections.emptyList();
    }//ww w.  ja  va  2  s.c  o m

    DeviceId deviceId = handler().data().deviceId();

    Bmv2DeviceAgent deviceAgent;
    try {
        deviceAgent = controller.getAgent(deviceId);
    } catch (Bmv2RuntimeException e) {
        log.error("Failed to get BMv2 device agent: {}", e.explain());
        return Collections.emptyList();
    }

    Bmv2DeviceContext context = contextService.getContext(deviceId);
    if (context == null) {
        log.warn("Unable to get device context for {}", deviceId);
    }

    Bmv2Interpreter interpreter = context.interpreter();
    Bmv2Configuration configuration = context.configuration();

    List<FlowEntry> entryList = Lists.newArrayList();

    for (Bmv2TableModel table : configuration.tables()) {
        // For each table in the configuration AND exposed by the interpreter.
        if (!interpreter.tableIdMap().inverse().containsKey(table.name())) {
            continue; // next table
        }

        List<Bmv2ParsedTableEntry> installedEntries;
        try {
            installedEntries = deviceAgent.getTableEntries(table.name());
        } catch (Bmv2RuntimeException e) {
            log.warn("Failed to get table entries of table {} of {}: {}", table.name(), deviceId, e.explain());
            continue; // next table
        }

        for (Bmv2ParsedTableEntry parsedEntry : installedEntries) {
            Bmv2TableEntryReference entryRef = new Bmv2TableEntryReference(deviceId, table.name(),
                    parsedEntry.matchKey());

            Lock lock = ENTRY_LOCKS.computeIfAbsent(entryRef, key -> new ReentrantLock());
            lock.lock();

            try {
                Bmv2FlowRuleWrapper frWrapper = tableEntryService.lookup(entryRef);

                if (frWrapper == null) {
                    log.debug(
                            "Missing reference from table entry service. Deleting it. BUG? "
                                    + "deviceId={}, tableName={}, matchKey={}",
                            deviceId, table.name(), entryRef.matchKey());
                    try {
                        doRemove(deviceAgent, table.name(), parsedEntry.entryId(), parsedEntry.matchKey());
                    } catch (Bmv2RuntimeException e) {
                        log.warn("Unable to remove inconsistent flow rule: {}", e.explain());
                    }
                    continue; // next entry
                }

                long remoteEntryId = parsedEntry.entryId();
                long localEntryId = frWrapper.entryId();

                if (remoteEntryId != localEntryId) {
                    log.debug(
                            "getFlowEntries(): inconsistent entry id! BUG? Updating it... remote={}, local={}",
                            remoteEntryId, localEntryId);
                    frWrapper = new Bmv2FlowRuleWrapper(frWrapper.rule(), remoteEntryId,
                            frWrapper.installedOnMillis());
                    tableEntryService.bind(entryRef, frWrapper);
                }

                long bytes = 0L;
                long packets = 0L;

                if (table.hasCounters()) {
                    // Read counter values from device.
                    try {
                        Pair<Long, Long> counterValue = deviceAgent.readTableEntryCounter(table.name(),
                                remoteEntryId);
                        bytes = counterValue.getLeft();
                        packets = counterValue.getRight();
                    } catch (Bmv2RuntimeException e) {
                        log.warn("Unable to get counters for entry {}/{} of device {}: {}", table.name(),
                                remoteEntryId, deviceId, e.explain());
                    }
                }

                FlowEntry entry = new DefaultFlowEntry(frWrapper.rule(), ADDED, frWrapper.lifeInSeconds(),
                        packets, bytes);
                entryList.add(entry);

            } finally {
                lock.unlock();
            }
        }
    }

    return Collections.unmodifiableCollection(entryList);
}