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

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

Introduction

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

Prototype

boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

Source Link

Document

Acquires the lock if it is free within the given waiting time and the current thread has not been Thread#interrupt interrupted .

Usage

From source file:org.orbeon.oxf.xforms.state.XFormsStateManager.java

/**
 * Return the locked document lock. Must be called before beforeUpdate().
 *
 * @param parameters    incoming Ajax request
 * @return              the document lock, already locked
 *//*from  w  w  w .  j a v  a  2  s.  com*/
public Lock acquireDocumentLock(RequestParameters parameters, long timeout) {
    assert parameters.getUUID() != null;

    // Check that the session is associated with the requested UUID. This enforces the rule that an incoming request
    // for a given UUID must belong to the same session that created the document. If the session expires, the
    // key goes away as well, and the key won't be present. If we don't do this check, the XForms server might
    // handle requests for a given UUID within a separate session, therefore providing access to other sessions,
    // which is not desirable. Further, we now have a lock stored in the session.
    final Lock lock = getDocumentLock(parameters.getUUID());
    if (lock == null)
        throw new SessionExpiredException("Unknown form document requested.");

    // Lock document for at most the max retry delay plus an increment
    try {
        final boolean acquired = lock.tryLock(timeout, TimeUnit.MILLISECONDS);
        if (acquired)
            return lock;
        else
            return null;
    } catch (InterruptedException e) {
        throw new OXFException(e);
    }
}

From source file:org.paxml.control.MutexTag.java

/**
 * {@inheritDoc}/*from  www. j a v  a 2  s  .c om*/
 */
@Override
protected Object doExecute(Context context) {
    String lockName = name == null ? null : name.evaluateString(context);
    if (lockName == null) {
        lockName = "";
    }
    Long timeoutValue = timeout == null ? null : ReflectUtils.coerceType(timeout.evaluate(context), Long.class);
    if (timeoutValue == null) {
        timeoutValue = DEFAULT_TIMEOUT;
    }
    Lock lock = getLock(lockName);

    if (log.isInfoEnabled()) {
        log.info("Waiting to enter mutex '" + lockName + "', timeout: " + timeoutValue);
    }
    long start = System.currentTimeMillis();
    long duration = 0;
    try {

        if (!lock.tryLock(timeoutValue, TimeUnit.MILLISECONDS)) {
            throw new PaxmlRuntimeException(
                    "Cannot enter mutex after waiting for " + timeoutValue + " ms, mutex name: " + lockName);
        }
        duration = System.currentTimeMillis() - start;
        start = System.currentTimeMillis();
        if (log.isInfoEnabled()) {

            log.info("Mutex '" + lockName + "' entered after waiting for " + duration + " ms");
        }
    } catch (InterruptedException e) {
        throw new PaxmlRuntimeException("Mutex entering interrupted, mutex name: " + lockName, e);
    }

    try {

        return super.doExecute(context);
    } finally {
        lock.unlock();
        if (log.isInfoEnabled()) {
            duration = System.currentTimeMillis() - start;
            log.info("Mutex '" + lockName + "' exited after being used for " + duration + " ms");
        }
    }

}

From source file:org.pepstock.jem.gwt.server.services.CommonResourcesManager.java

/**
 * Gets all resources list defined in JEM
 * /*from  w  w  w.j  a  va 2 s  . c  o  m*/
 * @param filter
 *            filter of resources
 * @return collection of resources
 * @throws ServiceMessageException
 * @throws Exception
 *             if any exception occurs
 */
public Collection<Resource> values(String filter) throws ServiceMessageException {
    // checks if the user is authorized to read resources information
    // if not, this method throws an exception
    checkAuthorization(new StringPermission(Permissions.RESOURCES_READ));

    IMap<String, Resource> map = getInstance().getMap(Queues.COMMON_RESOURCES_MAP);
    // creates a Resource predicate
    // using filter filled on UI
    ResourcePredicate predicate;
    try {
        predicate = new ResourcePredicate(Filter.parse(filter));
    } catch (Exception e) {
        LogAppl.getInstance().debug(e.getMessage(), e);
        // default case, all resources with empty filter by name
        Filter all = new Filter();
        all.add(new FilterToken(ResourceFilterFields.NAME.getName(), StringUtils.EMPTY));
        predicate = new ResourcePredicate(all);
    }

    Collection<Resource> result = null;
    // locks all map to have a consistent collection
    // only for 10 seconds otherwise
    // throws an exception
    boolean isLock = false;
    Lock lock = getInstance().getLock(Queues.COMMON_RESOURCES_MAP_LOCK);
    try {
        isLock = lock.tryLock(10, TimeUnit.SECONDS);
        if (isLock) {
            // performs predicate to have the collection
            result = map.values(predicate);
        } else {
            // timeout exception
            throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, Queues.COMMON_RESOURCES_MAP);
        }
    } catch (InterruptedException e) {
        throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, e, Queues.COMMON_RESOURCES_MAP);
    } finally {
        // unlocks always the map
        if (isLock) {
            lock.unlock();
        }
    }
    // returns a collection
    return result;

}

From source file:org.pepstock.jem.gwt.server.services.NodesManager.java

private List<NodeInfoBean> getNodesButUnknown(AbstractPredicate predicate) throws ServiceMessageException {
    IMap<String, NodeInfo> nodes = getInstance().getMap(Queues.NODES_MAP);
    List<NodeInfoBean> list = new ArrayList<NodeInfoBean>();
    Collection<NodeInfo> allNodes = null;
    boolean isLock = false;
    Lock lock = getInstance().getLock(Queues.NODES_MAP_LOCK);
    try {/*from   w  w w.  java  2 s  .co  m*/
        isLock = lock.tryLock(10, TimeUnit.SECONDS);
        if (isLock) {
            // gets all nodes by predicate
            allNodes = nodes.values(predicate);
        } else {
            throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, Queues.NODES_MAP);
        }
    } catch (InterruptedException e) {
        throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, e, Queues.NODES_MAP);
    } finally {
        // unlocks always the map
        if (isLock) {
            lock.unlock();
        }
    }
    if (allNodes != null) {
        // gets the nodes and returns them
        // removing the nodes in UNKNOW
        // to avoid misunderstanding on UI
        for (NodeInfo node : allNodes) {
            if (!node.getStatus().equals(Status.UNKNOWN)) {
                list.add(node.getNodeInfoBean());
            }
        }
    }
    return list;
}

From source file:org.pepstock.jem.gwt.server.services.RolesManager.java

/**
 * Returns a collection of roles, by a filter (a set of key-values).
 * /*from ww  w. j a  v a  2s . c om*/
 * @param filter
 *            string which contains a set of key-values
 * @return a collection of roles, matching the filter
 * @throws ServiceMessageException
 *             if any exception occurs
 */
public Collection<Role> getRoles(String filter) throws ServiceMessageException {
    // checks if the user is authorized to read roles
    // if not, this method throws an exception
    checkAuthorization(new StringPermission(Permissions.ROLES_READ));

    IMap<String, Role> roles = getInstance().getMap(Queues.ROLES_MAP);
    RolePredicate predicate;
    try {
        // creates predicate by filter string
        predicate = new RolePredicate(Filter.parse(filter));
    } catch (Exception e) {
        LogAppl.getInstance().debug(e.getMessage(), e);
        // default case, all roles
        Filter all = new Filter();
        all.add(new FilterToken(RoleFilterFields.NAME.getName(), StringUtils.EMPTY));
        predicate = new RolePredicate(all);
    }

    List<Role> list = null;
    // locks all map to have a consistent collection
    // only for 10 seconds otherwise
    // throws an exception
    boolean isLock = false;
    Lock lock = getInstance().getLock(Queues.ROLES_MAP_LOCK);
    try {
        isLock = lock.tryLock(10, TimeUnit.SECONDS);
        if (isLock) {
            // applies predicate
            list = new ArrayList<Role>(roles.values(predicate));
        } else {
            throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, Queues.ROLES_MAP);
        }
    } catch (InterruptedException e) {
        throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, e, Queues.ROLES_MAP);
    } finally {
        // unlocks always the map
        if (isLock) {
            lock.unlock();
        }
    }
    return list;
}

From source file:org.pepstock.jem.gwt.server.services.StatisticsManager.java

/**
 * Returns the collection of all active samples in JEM. 
 * /*  w w  w  . ja  v a 2s  .  co m*/
  * @return collection of samples
 * @throws ServiceMessageException if any exception occurs
  */
public Collection<LightSample> getSamples() throws ServiceMessageException {
    // Remember that it uses QUEUES CURRENT permission to check if
    // it can get statistics
    // checks if the user is authorized
    // if not, this method throws an exception
    try {
        checkAuthorization(new StringPermission(Permissions.ADMINISTRATION_CLUSTER_FOLDER));
    } catch (Exception e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
        try {
            checkAuthorization(new StringPermission(Permissions.ADMINISTRATION_NODES_FOLDER));
        } catch (Exception e1) {
            LogAppl.getInstance().ignore(e1.getMessage(), e1);
            checkAuthorization(new StringPermission(Permissions.ADMINISTRATION_QUEUES_FOLDER));
        }
    }
    IMap<String, LightSample> samples = getInstance().getMap(Queues.STATS_MAP);
    Lock lock = getInstance().getLock(Queues.STATS_MAP_LOCK);
    boolean isLock = false;
    List<LightSample> list = null;
    try {
        // locks all map to have a consistent collection
        // only for 10 seconds otherwise
        // throws an exception
        isLock = lock.tryLock(10, TimeUnit.SECONDS);
        if (isLock) {
            // gets data...
            list = new ArrayList<LightSample>(samples.values());
            // ... and sorts them
            Collections.sort(list, sampleComparator);
        } else {
            // timeout exception
            throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, Queues.STATS_MAP_LOCK);
        }
    } catch (InterruptedException e) {
        // timeout exception
        throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, e, Queues.STATS_MAP_LOCK);
    } finally {
        // unlocks always the map
        if (isLock) {
            lock.unlock();
        }
    }
    return list;
}

From source file:org.pepstock.jem.node.JclCheckingQueueManager.java

/**
 * Loads all roles assigned to the user of job
 * @param user user of job //from ww w . j av a2  s . c  om
 * @return list of roles of user
 * @throws NodeMessageException is any error occurs during getting the roles
 */
private List<Role> loadRoles(User user) throws NodeMessageException {
    // creates Hazelcast predicate to extract all roles and permissions
    // assigned to user
    RolesQueuePredicate predicate = new RolesQueuePredicate();
    predicate.setUser(user);

    // gets HC map for roles
    IMap<String, Role> roles = Main.getHazelcast().getMap(Queues.ROLES_MAP);
    // locks in HC to have a consistent status on roles
    Lock lock = Main.getHazelcast().getLock(Queues.ROLES_MAP_LOCK);
    List<Role> myroles = null;
    boolean isLock = false;
    try {
        // locks the map, if not EXCEPTION!!
        isLock = lock.tryLock(10, TimeUnit.SECONDS);
        if (isLock) {
            // reads the roles of the job user
            myroles = new ArrayList<Role>(roles.values(predicate));
        } else {
            throw new NodeMessageException(NodeMessage.JEMC119E, Queues.ROLES_MAP);
        }
    } catch (Exception e) {
        throw new NodeMessageException(NodeMessage.JEMC119E, e, Queues.ROLES_MAP);
    } finally {
        // always unlock 
        if (isLock) {
            lock.unlock();
        }
    }
    return myroles;
}

From source file:org.pepstock.jem.node.persistence.RecoveryManager.java

/**
 * Applies all redo statements from Hazelcast map 
 * @return true if apply statements// w  w  w.  j a v a2s  .  c o  m
 * @throws MessageException if any errors occurs during the apply of redo statements
 * 
 */
public boolean applyRedoStatements() throws MessageException {
    // gets the HC map
    IMap<Long, RedoStatement> redoMap = Main.getHazelcast().getMap(Queues.REDO_STATEMENT_MAP);
    // locks inetrnally of JEM cluster
    Lock lock = Main.getHazelcast().getLock(Queues.REDO_STATEMENT_MAP_LOCK);
    boolean isLock = false;
    try {
        // gets a lock
        isLock = lock.tryLock(10, TimeUnit.SECONDS);
        if (isLock) {
            // if map of redo statements is empty
            // means nothing to apply
            if (redoMap.isEmpty()) {
                return false;
            }
            // reads all redo statements
            List<RedoStatement> values = new ArrayList<RedoStatement>(redoMap.values());
            // sorts by ID
            // in this ways it can apply all redo statements on the right order
            // how they have been created
            Collections.sort(values, new Comparator<RedoStatement>() {
                @Override
                public int compare(RedoStatement rd0, RedoStatement rd1) {
                    return rd0.getId().compareTo(rd1.getId());
                }
            });
            // scans all redo statements
            for (RedoStatement statement : values) {
                // extracts the map store of HC
                // using the queue information of redo statement
                JobMapManager mapStore = null;
                if (statement.getQueueName().equalsIgnoreCase(Queues.INPUT_QUEUE)) {
                    mapStore = InputMapManager.getInstance();
                } else if (statement.getQueueName().equalsIgnoreCase(Queues.RUNNING_QUEUE)) {
                    mapStore = RunningMapManager.getInstance();
                } else if (statement.getQueueName().equalsIgnoreCase(Queues.OUTPUT_QUEUE)) {
                    mapStore = OutputMapManager.getInstance();
                } else if (statement.getQueueName().equalsIgnoreCase(Queues.ROUTING_QUEUE)) {
                    mapStore = RoutingMapManager.getInstance();
                }
                // if action is store, it calls the store method
                // of map store
                // otherwise it calls the delete one
                if (statement.getAction().equalsIgnoreCase(RedoStatement.STORE)) {
                    mapStore.store(statement.getJob().getId(), statement.getJob(), true);
                } else if (statement.getAction().equalsIgnoreCase(RedoStatement.DELETE)) {
                    mapStore.delete(statement.getJobId(), true);
                }
                // remove the redo statement from HC map
                redoMap.remove(statement.getId());
                // shows the redo has been ended correctly
                LogAppl.getInstance().emit(NodeMessage.JEMC176I, statement.toString());
            }
            LogAppl.getInstance().emit(NodeMessage.JEMC177I, String.valueOf(values.size()));
            // all redo has been done correctly
            return true;
        } else {
            throw new MessageException(NodeMessage.JEMC119E, Queues.REDO_STATEMENT_MAP);
        }
    } catch (Exception e) {
        throw new MessageException(NodeMessage.JEMC119E, e, Queues.REDO_STATEMENT_MAP);
    } finally {
        // always unlock the lock on REDO
        if (isLock) {
            lock.unlock();
        }
    }
}

From source file:org.pepstock.jem.node.StartUpSystem.java

/**
 * Load the persisted queues by calling them for the first time.
 * //  www .  ja va2s .  c om
 * @throws ConfigurationException
 */
private static void loadQueues() throws ConfigurationException {
    // loads all keys for INPUT, RUNNING, OUTPUT, ROUTING and
    // CommonResources. this
    // call of method
    // will schedule the call on persistent manager
    IMap<String, Job> inputQueue = Main.getHazelcast().getMap(Queues.INPUT_QUEUE);
    inputQueue.size();

    IMap<String, Job> outputQueue = Main.getHazelcast().getMap(Queues.OUTPUT_QUEUE);
    outputQueue.size();

    // this code removes all jobs in running queue if the node is
    // coordinator
    // this is necessary if the cluster crashed due to a failure
    if (Main.IS_COORDINATOR.get()) {
        IMap<String, Job> runningQueue = Main.getHazelcast().getMap(Queues.RUNNING_QUEUE);

        Lock lock = Main.getHazelcast().getLock(Queues.RUNNING_QUEUE_LOCK);
        boolean isLock = false;
        try {
            isLock = lock.tryLock(10, TimeUnit.SECONDS);
            if (!runningQueue.isEmpty()) {
                for (Job job : runningQueue.values()) {
                    org.pepstock.jem.Result result = new org.pepstock.jem.Result();
                    result.setReturnCode(org.pepstock.jem.Result.FATAL);
                    result.setExceptionMessage("Node is crashed during job was executing");
                    job.setResult(result);
                    job.setEndedTime(new Date());
                    job.setRunningStatus(Job.NONE);
                    LogAppl.getInstance().emit(NodeMessage.JEMC190W, job.getName(), job.getId());
                    runningQueue.remove(job.getId());
                    outputQueue.putIfAbsent(job.getId(), job);
                }
            }
        } catch (Exception e) {
            throw new ConfigurationException(e);
        } finally {
            if (isLock) {
                lock.unlock();
            }
        }
        // Clean up of nodes map store
        NodeInfoUtility.checkAndCleanMapStore();
    }

    IMap<String, Job> routingQueue = Main.getHazelcast().getMap(Queues.ROUTING_QUEUE);
    routingQueue.size();

    RecoveryManager.getInstance();

    IMap<String, Resource> resourceMap = Main.getHazelcast().getMap(Queues.COMMON_RESOURCES_MAP);
    resourceMap.size();

    IMap<String, Role> rolesMap = Main.getHazelcast().getMap(Queues.ROLES_MAP);
    rolesMap.size();

    IMap<String, SwarmConfiguration> routingConfigMap = Main.getHazelcast().getMap(Queues.ROUTING_CONFIG_MAP);
    routingConfigMap.size();

    // if map is emtpy, a DEFAULT routing config will be added
    if (routingConfigMap.isEmpty()) {
        routingConfigMap.put(SwarmConfiguration.DEFAULT_NAME, new SwarmConfiguration());
    }

    IMap<String, Map<String, UserPreference>> userPreferencesMap = Main.getHazelcast()
            .getMap(Queues.USER_PREFERENCES_MAP);
    userPreferencesMap.size();

}

From source file:org.pepstock.jem.node.tasks.JobTask.java

/**
 * Loads all roles defined for a specific user.
 * @param user user to extract its roles
 * @return a list of roles assigned to the user
 * @throws NodeMessageException if any error occurs retrievin gthe roles
 *//*w  w  w.ja  va2s  .co  m*/
private List<Role> loadRoles(User user) throws NodeMessageException {
    // creates Hazelcast predicate to extract all roles and permissions
    // assigned to user
    RolesQueuePredicate predicate = new RolesQueuePredicate();
    predicate.setUser(user);

    List<Role> myroles = null;
    // gets map and performs predicate!
    IMap<String, Role> rolesMap = Main.getHazelcast().getMap(Queues.ROLES_MAP);
    Lock lock = Main.getHazelcast().getLock(Queues.ROLES_MAP_LOCK);
    boolean isLock = false;
    try {
        isLock = lock.tryLock(10, TimeUnit.SECONDS);
        if (isLock) {
            myroles = new ArrayList<Role>(rolesMap.values(predicate));
        } else {
            throw new NodeMessageException(NodeMessage.JEMC119E, Queues.ROLES_MAP);
        }
    } catch (Exception e) {
        throw new NodeMessageException(NodeMessage.JEMC119E, e, Queues.ROLES_MAP);
    } finally {
        if (isLock) {
            lock.unlock();
        }
    }
    return myroles;
}