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:example.pki.VaultPkiConfiguration.java

/**
 * Obtain SSL certificate (cached/request new certificate) with startup locking.
 *
 * @param vaultProperties/* w w  w  . j av a 2  s  .  c  o  m*/
 * @param vaultOperations
 * @param pkiProperties
 * @param serverProperties
 * @param synchronizationProvider
 * @return
 * @throws Exception
 */
@Bean
@ConditionalOnProperty(prefix = "server.ssl", name = "enabled", havingValue = "true")
public static SslCertificateEmbeddedServletContainerCustomizer sslCertificateRequestingPostProcessor(
        VaultProperties vaultProperties, VaultOperations vaultOperations, VaultPkiProperties pkiProperties,
        ServerProperties serverProperties, SynchronizationProvider synchronizationProvider) throws Exception {

    Lock lock = synchronizationProvider.getLock();

    CertificateBundle certificateBundle = CertificateUtil.findValidCertificate(vaultProperties, vaultOperations,
            pkiProperties);

    if (certificateBundle != null) {
        return createCustomizer(serverProperties, certificateBundle);
    }

    boolean locked = lock.tryLock(pkiProperties.getStartupLockTimeout(), TimeUnit.MILLISECONDS);

    if (!locked) {
        throw new IllegalStateException(String.format("Could not obtain SSL synchronization lock within %d %s",
                pkiProperties.getStartupLockTimeout(), TimeUnit.MILLISECONDS));
    }

    try {
        certificateBundle = CertificateUtil.getOrRequestCertificate(vaultProperties, vaultOperations,
                pkiProperties);

        return createCustomizer(serverProperties, certificateBundle);
    } finally {
        lock.unlock();
    }

}

From source file:com.mycollab.module.ecm.service.impl.DriveInfoServiceImpl.java

@Override
public void saveOrUpdateDriveInfo(@CacheKey DriveInfo driveInfo) {
    Integer sAccountId = driveInfo.getSaccountid();
    DriveInfoExample ex = new DriveInfoExample();
    ex.createCriteria().andSaccountidEqualTo(sAccountId);
    Lock lock = DistributionLockUtil.getLock("ecm-service" + sAccountId);
    try {/*from  ww  w.java 2 s  .  c  o m*/
        if (lock.tryLock(15, TimeUnit.SECONDS)) {
            if (driveInfoMapper.countByExample(ex) > 0) {
                driveInfo.setId(null);
                driveInfoMapper.updateByExampleSelective(driveInfo, ex);
            } else {
                driveInfoMapper.insert(driveInfo);
            }
        }
    } catch (Exception e) {
        LOG.error("Error while save drive info " + BeanUtility.printBeanObj(driveInfo), e);
    } finally {
        DistributionLockUtil.removeLock("ecm-service" + sAccountId);
        lock.unlock();
    }
}

From source file:com.esofthead.mycollab.module.ecm.esb.impl.DeleteResourcesCommandImpl.java

@Override
public void removeResource(String[] paths, String userDelete, Integer sAccountId) {

    Lock lock = DistributionLockUtil.getLock("ecm-" + sAccountId);
    if (sAccountId == null) {
        return;// ww w . j av a2s  .co  m
    }
    try {
        if (lock.tryLock(1, TimeUnit.HOURS)) {
            long totalSize = 0;
            DriveInfo driveInfo = driveInfoService.getDriveInfo(sAccountId);

            for (String path : paths) {
                if (StringUtils.isBlank(path)) {
                    continue;
                }
                totalSize += rawContentService.getSize(path);
                rawContentService.removePath(path);
            }

            if (driveInfo.getUsedvolume() == null || (driveInfo.getUsedvolume() < totalSize)) {
                LOG.error(
                        "Inconsistent storage volumne site of account {}, used storage is less than removed storage ",
                        sAccountId);
                driveInfo.setUsedvolume(0L);
            } else {
                driveInfo.setUsedvolume(driveInfo.getUsedvolume() - totalSize);
            }

            driveInfoService.saveOrUpdateDriveInfo(driveInfo);
        }
    } catch (Exception e) {
        LOG.error("Error while delete content " + paths, e);
    } finally {
        lock.unlock();
    }
}

From source file:com.esofthead.mycollab.module.ecm.esb.impl.SaveContentCommandImpl.java

@Override
public void saveContent(Content content, String createdUser, Integer sAccountId) {
    LOG.debug("Save content {} by {}", BeanUtility.printBeanObj(content), createdUser);
    if (sAccountId == null) {
        return;/*from  w ww.  j av  a 2  s. co m*/
    }

    Lock lock = DistributionLockUtil.getLock("ecm-" + sAccountId);
    long totalSize = content.getSize();

    if (StringUtils.isNotBlank(content.getThumbnail())) {
        totalSize += rawContentService.getSize(content.getThumbnail());
    }

    try {
        if (lock.tryLock(1, TimeUnit.HOURS)) {
            DriveInfo driveInfo = driveInfoService.getDriveInfo(sAccountId);
            if (driveInfo.getUsedvolume() == null) {
                driveInfo.setUsedvolume(totalSize);
            } else {
                driveInfo.setUsedvolume(totalSize + driveInfo.getUsedvolume());
            }

            driveInfoService.saveOrUpdateDriveInfo(driveInfo);
        }
    } catch (Exception e) {
        LOG.error("Error while save content " + BeanUtility.printBeanObj(content), e);
    } finally {
        lock.unlock();
    }
}

From source file:net.solarnetwork.node.io.rxtx.RxtxDataCollectorFactory.java

private Lock acquireLock() throws LockTimeoutException {
    log.debug("Acquiring lock on port {}; waiting at most {} {}",
            new Object[] { portIdentifier, timeout, unit });
    synchronized (PORT_LOCKS) {
        if (!PORT_LOCKS.containsKey(portIdentifier)) {
            PORT_LOCKS.put(portIdentifier, new ReentrantLock(true));
        }//from  ww  w .  ja  va  2  s .  c o  m
        Lock lock = PORT_LOCKS.get(portIdentifier);
        try {
            if (lock.tryLock(timeout, unit)) {
                log.debug("Acquired port {} lock", portIdentifier);
                return lock;
            }
            log.debug("Timeout acquiring port {} lock", portIdentifier);
        } catch (InterruptedException e) {
            log.debug("Interrupted waiting for port {} lock", portIdentifier);
        }
    }
    throw new LockTimeoutException("Could not acquire port " + portIdentifier + " lock");
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

@Override
public void massDeletePredecessors(List<TaskPredecessor> predecessors, @CacheKey Integer sAccountId) {
    Lock lock = DistributionLockUtil.getLock("gantt-predecessor-service" + sAccountId);
    try {/*from www  .ja  va 2  s  .  c om*/
        if (lock.tryLock(30, TimeUnit.SECONDS)) {
            try (Connection connection = dataSource.getConnection()) {
                connection.setAutoCommit(false);
                PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM "
                        + "`m_prj_predecessor` WHERE sourceType=? AND predestype=? AND sourceId=? AND descId=? AND descType=?");
                for (int i = 0; i < predecessors.size(); i++) {
                    preparedStatement.setString(1, predecessors.get(i).getSourcetype());
                    preparedStatement.setString(2, predecessors.get(i).getPredestype());
                    preparedStatement.setInt(3, predecessors.get(i).getSourceid());
                    preparedStatement.setInt(4, predecessors.get(i).getDescid());
                    preparedStatement.setString(5, predecessors.get(i).getDesctype());
                    preparedStatement.addBatch();
                }
                preparedStatement.executeBatch();
                connection.commit();
            }
        }
    } catch (Exception e) {
        throw new MyCollabException(e);
    } finally {
        DistributionLockUtil.removeLock("gantt-predecessor-service" + sAccountId);
        lock.unlock();
    }
}

From source file:com.reactive.hzdfs.dll.AbstractFileSharingService.java

/**
 * Distributed lock//from   w  w w  . j av  a2 s .co  m
 * @param duration
 * @param unit
 * @return
 * @throws InterruptedException
 */
private boolean tryLock(long duration, TimeUnit unit) throws InterruptedException {
    Lock lock = hzService.getClusterLock("FileSharingAgent");
    return lock.tryLock(duration, unit);
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

private void massUpdateBugGanttItems(final List<TaskGanttItem> taskGanttItems, Integer sAccountId) {
    if (CollectionUtils.isNotEmpty(taskGanttItems)) {
        Lock lock = DistributionLockUtil.getLock("gantt-bug-service" + sAccountId);
        try {/* w  ww.ja v  a 2s.com*/
            final long now = new GregorianCalendar().getTimeInMillis();
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                try (Connection connection = dataSource.getConnection()) {
                    connection.setAutoCommit(false);
                    PreparedStatement batchTasksStatement = connection.prepareStatement(
                            "UPDATE `m_tracker_bug` SET " + "summary = ?, `startdate` = ?, `enddate` = ?, "
                                    + "`lastUpdatedTime`=?, `percentagecomplete`=?, `assignuser`=?, `ganttindex`=?, "
                                    + "`milestoneId`=? WHERE `id` = ?");
                    for (int i = 0; i < taskGanttItems.size(); i++) {
                        TaskGanttItem ganttItem = taskGanttItems.get(i);
                        if (ProjectTypeConstants.BUG.equals(ganttItem.getType())) {
                            batchTasksStatement.setString(1, ganttItem.getName());
                            batchTasksStatement.setDate(2, getDateWithNullValue(ganttItem.getStartDate()));
                            batchTasksStatement.setDate(3, getDateWithNullValue(ganttItem.getEndDate()));
                            batchTasksStatement.setDate(4, new Date(now));
                            batchTasksStatement.setDouble(5,
                                    MoreObjects.firstNonNull(ganttItem.getProgress(), 0d));
                            batchTasksStatement.setString(6, ganttItem.getAssignUser());
                            batchTasksStatement.setInt(7, ganttItem.getGanttIndex());
                            batchTasksStatement.setObject(8, ganttItem.getMilestoneId());
                            batchTasksStatement.setInt(9, ganttItem.getId());
                            batchTasksStatement.addBatch();
                        }

                    }
                    batchTasksStatement.executeBatch();
                    connection.commit();
                }
            }
        } catch (Exception e) {
            throw new MyCollabException(e);
        } finally {
            DistributionLockUtil.removeLock("gantt-bug-service" + sAccountId);
            lock.unlock();
        }
    }
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

private void massUpdateTaskGanttItems(final List<TaskGanttItem> taskGanttItems, Integer sAccountId) {
    if (CollectionUtils.isNotEmpty(taskGanttItems)) {
        Lock lock = DistributionLockUtil.getLock("gantt-task-service" + sAccountId);
        try {//from www  .  j ava  2 s . co m
            final long now = new GregorianCalendar().getTimeInMillis();
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                try (Connection connection = dataSource.getConnection()) {
                    connection.setAutoCommit(false);
                    PreparedStatement batchTasksStatement = connection.prepareStatement(
                            "UPDATE `m_prj_task` SET " + "taskname = ?, `startdate` = ?, `enddate` = ?, "
                                    + "`lastUpdatedTime`=?, `percentagecomplete`=?, `assignUser`=?, `ganttindex`=?, "
                                    + "`milestoneId`=?, `parentTaskId`=? WHERE `id` = ?");
                    for (int i = 0; i < taskGanttItems.size(); i++) {
                        TaskGanttItem ganttItem = taskGanttItems.get(i);
                        if (ProjectTypeConstants.TASK.equals(ganttItem.getType())) {
                            batchTasksStatement.setString(1, ganttItem.getName());
                            batchTasksStatement.setDate(2, getDateWithNullValue(ganttItem.getStartDate()));
                            batchTasksStatement.setDate(3, getDateWithNullValue(ganttItem.getEndDate()));
                            batchTasksStatement.setDate(4, new Date(now));
                            batchTasksStatement.setDouble(5, ganttItem.getProgress());
                            batchTasksStatement.setString(6, ganttItem.getAssignUser());
                            batchTasksStatement.setInt(7, ganttItem.getGanttIndex());
                            batchTasksStatement.setObject(8, ganttItem.getMilestoneId());
                            batchTasksStatement.setObject(9, ganttItem.getParentTaskId());
                            batchTasksStatement.setInt(10, ganttItem.getId());
                            batchTasksStatement.addBatch();
                        }

                    }
                    batchTasksStatement.executeBatch();
                    connection.commit();
                }
            }
        } catch (Exception e) {
            throw new MyCollabException(e);
        } finally {
            DistributionLockUtil.removeLock("gantt-task-service" + sAccountId);
            lock.unlock();
        }
    }
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

private void massUpdateMilestoneGanttItems(final List<MilestoneGanttItem> milestoneGanttItems,
        Integer sAccountId) {/* w  w w .  j  a  va2s  . co  m*/
    if (CollectionUtils.isNotEmpty(milestoneGanttItems)) {
        Lock lock = DistributionLockUtil.getLock("gantt-milestone-service" + sAccountId);
        try {
            final long now = new GregorianCalendar().getTimeInMillis();
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                try (Connection connection = dataSource.getConnection()) {
                    connection.setAutoCommit(false);
                    PreparedStatement preparedStatement = connection.prepareStatement(
                            "UPDATE `m_prj_milestone` SET " + "name = ?, `startdate` = ?, `enddate` = ?, "
                                    + "`lastUpdatedTime`=?, `owner`=?, `ganttIndex`=? WHERE `id` = ?");
                    for (int i = 0; i < milestoneGanttItems.size(); i++) {
                        preparedStatement.setString(1, milestoneGanttItems.get(i).getName());
                        preparedStatement.setDate(2,
                                getDateWithNullValue(milestoneGanttItems.get(i).getStartDate()));
                        preparedStatement.setDate(3,
                                getDateWithNullValue(milestoneGanttItems.get(i).getEndDate()));
                        preparedStatement.setDate(4, new Date(now));
                        preparedStatement.setString(5, milestoneGanttItems.get(i).getAssignUser());
                        preparedStatement.setInt(6, milestoneGanttItems.get(i).getGanttIndex());
                        preparedStatement.setInt(7, milestoneGanttItems.get(i).getId());
                        preparedStatement.addBatch();

                    }
                    preparedStatement.executeBatch();
                    connection.commit();
                }
            }
        } catch (Exception e) {
            throw new MyCollabException(e);
        } finally {
            DistributionLockUtil.removeLock("gantt-milestone-service" + sAccountId);
            lock.unlock();
        }
    }
}