当前位置: 首页>>代码示例>>Java>>正文


Java InterProcessMutex类代码示例

本文整理汇总了Java中org.apache.curator.framework.recipes.locks.InterProcessMutex的典型用法代码示例。如果您正苦于以下问题:Java InterProcessMutex类的具体用法?Java InterProcessMutex怎么用?Java InterProcessMutex使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


InterProcessMutex类属于org.apache.curator.framework.recipes.locks包,在下文中一共展示了InterProcessMutex类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: DbleServer

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
private DbleServer() {
    this.config = new ServerConfig();
    scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat("TimerScheduler-%d").build());

    /*
     * | offline | Change Server status to OFF |
     * | online | Change Server status to ON |
     */
    this.isOnline = new AtomicBoolean(true);


    // load data node active index from properties
    dnIndexProperties = DnPropertyUtil.loadDnIndexProps();

    this.startupTime = TimeUtil.currentTimeMillis();
    if (isUseZkSwitch()) {
        dnIndexLock = new InterProcessMutex(ZKUtils.getConnection(), KVPathUtil.getDnIndexLockPath());
    }
    xaSessionCheck = new XASessionCheck();
}
 
开发者ID:actiontech,项目名称:dble,代码行数:21,代码来源:DbleServer.java

示例2: tryLock

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
@Override
public boolean tryLock(String key) {
    try {
        InterProcessMutex mutex = locks.computeIfAbsent(key,
                __ -> new InterProcessMutex(curatorFramework, String.join("/", basePath, key)));
        
        
        boolean owned = mutex.isAcquiredInThisProcess();
        if(owned) {
            return true;
        } else {
            mutex.acquire(timeout, TimeUnit.MILLISECONDS);
        }
        return mutex.isAcquiredInThisProcess();
    } catch (Exception e) {
        return false;
    }
}
 
开发者ID:benson-git,项目名称:ibole-microservice,代码行数:19,代码来源:DistributedLockServiceCuratorImpl.java

示例3: stateChanged

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
	
    switch (newState) {
    case LOST:
    case SUSPENDED:

        Collection<InterProcessMutex> oldLocks = new ArrayList<>(locks.values());
        locks.clear();

        oldLocks.stream().parallel().forEach(lock -> {
            try {
                lock.release();
            } catch (Exception e) {
                logger.trace("Can't release lock on " + newState);
            }
        });
        break;
    default:
    }
}
 
开发者ID:benson-git,项目名称:ibole-microservice,代码行数:22,代码来源:DistributedLockServiceCuratorImpl.java

示例4: inMutex

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
private static void inMutex(CuratorFramework curator, String mutexPath, Runnable work) {
    final InterProcessMutex mutex = new InterProcessMutex(curator, mutexPath);
    try {
        // try to acquire mutex for index within flush period
        if (mutex.acquire(LOCK_ACQUIRE_TIMEOUT.getMillis(), TimeUnit.MILLISECONDS)) {
            try {
                work.run();
            } finally {
                mutex.release();
            }
        } else {
            _log.warn("could not acquire index lock after {} millis!!", LOCK_ACQUIRE_TIMEOUT.getMillis());
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
 
开发者ID:bazaarvoice,项目名称:emodb,代码行数:18,代码来源:CreateKeyspacesCommand.java

示例5: tryLock

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
@Override
public boolean tryLock(String key) {
    try {
        InterProcessMutex mutex = locks.computeIfAbsent(key,
                __ -> new InterProcessMutex(curatorFramework, String.join("/", basePath, key)));


        boolean owned = mutex.isAcquiredInThisProcess();
        if(owned) {
            return true;
        } else {
            mutex.acquire(timeout, TimeUnit.MILLISECONDS);
        }
        return mutex.isAcquiredInThisProcess();
    } catch (Exception e) {
        return false;
    }
}
 
开发者ID:aol,项目名称:micro-server,代码行数:19,代码来源:DistributedLockServiceCuratorImpl.java

示例6: stateChanged

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {

    switch (newState) {
    case LOST:
    case SUSPENDED:

        Collection<InterProcessMutex> oldLocks = new ArrayList<>(locks.values());
        locks.clear();

        oldLocks.stream().parallel().forEach(lock -> {
            try {
                lock.release();
            } catch (Exception e) {
                logger.trace("Can't release lock on " + newState);
            }
        });
        break;
    default:
    }
}
 
开发者ID:aol,项目名称:micro-server,代码行数:22,代码来源:DistributedLockServiceCuratorImpl.java

示例7: runSetup

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
/**
 * Call each registered {@link SetupStep} one after the other.
 * @throws SetupException Thrown with any error during running setup, including Zookeeper interactions, and
 *                          individual failures in the {@link SetupStep}.
 */
@PostConstruct
public void runSetup() throws SetupException {
    HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration);
    InterProcessMutex lock = curatorFactory.lockInstance(zookeeperProperties.getZkRoot());
    try {
        LOG.info("Trying to acquire lock for running setup.");
        lock.acquire();
        LOG.info("Acquired lock for running setup.");
        handleSetupInProgress(configuration, zookeeperProperties);
        for (SetupStep step : setupSteps) {
            LOG.info("Running setup step: {}", step);
            step.run();
        }
        clearSetupInProgress(zookeeperProperties);
    } catch (SetupException se) {
        LOG.error("Got setup exception while trying to setup", se);
        throw se;
    } catch (Throwable e) {
        LOG.error("Error running setup steps", e);
        throw new SetupException("Error running setup steps", e);
    } finally {
        releaseLock(lock);
        curatorFactory.close();
    }
}
 
开发者ID:apache,项目名称:incubator-atlas,代码行数:31,代码来源:SetupSteps.java

示例8: shouldRunRegisteredSetupSteps

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
@Test
public void shouldRunRegisteredSetupSteps() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    SetupStep setupStep2 = mock(SetupStep.class);
    steps.add(setupStep1);
    steps.add(setupStep2);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    setupServerIdSelectionMocks();
    setupSetupInProgressPathMocks(ZooDefs.Ids.OPEN_ACL_UNSAFE);

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(setupStep1).run();
    verify(setupStep2).run();
}
 
开发者ID:apache,项目名称:incubator-atlas,代码行数:24,代码来源:SetupStepsTest.java

示例9: shouldCreateSetupInProgressNode

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
@Test
public void shouldCreateSetupInProgressNode() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("digest:user:pwd");

    List<ACL> aclList = Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:pwd")));
    setupServerIdSelectionMocks();
    CreateBuilder createBuilder = setupSetupInProgressPathMocks(aclList).getLeft();

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(createBuilder).withACL(aclList);
    verify(createBuilder).forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE,
            "id2".getBytes(Charsets.UTF_8));
}
 
开发者ID:apache,项目名称:incubator-atlas,代码行数:26,代码来源:SetupStepsTest.java

示例10: shouldDeleteSetupInProgressNodeAfterCompletion

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
@Test
public void shouldDeleteSetupInProgressNodeAfterCompletion() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("digest:user:pwd");

    List<ACL> aclList = Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:pwd")));
    setupServerIdSelectionMocks();
    DeleteBuilder deleteBuilder = setupSetupInProgressPathMocks(aclList).getRight();

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(deleteBuilder).forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE);
}
 
开发者ID:apache,项目名称:incubator-atlas,代码行数:24,代码来源:SetupStepsTest.java

示例11: shouldThrowSetupExceptionAndNotDoSetupIfSetupInProgressNodeExists

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
@Test
public void shouldThrowSetupExceptionAndNotDoSetupIfSetupInProgressNodeExists() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    setupServerIdSelectionMocks();
    setupSetupInProgressPathMocks(ZooDefs.Ids.OPEN_ACL_UNSAFE, mock(Stat.class));

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);

    try {
        setupSteps.runSetup();
    } catch (Exception e) {
        assertTrue(e instanceof SetupException);
    }

    verifyZeroInteractions(setupStep1);
}
 
开发者ID:apache,项目名称:incubator-atlas,代码行数:26,代码来源:SetupStepsTest.java

示例12: distributeLock

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
/**
 * 使用分布式锁执行任务
 *
 * @param path
 * @param getLockTimeout 获取锁超时时间(单位ms)
 * @param task
 * @auth anduo 2015年5月8日
 */
public void distributeLock(String path, int getLockTimeout, Runnable task) {
    InterProcessMutex lock = new InterProcessMutex(client, path);
    try {
        LOGGER.debug("尝试获取锁。。。");
        if (lock.acquire(getLockTimeout, TimeUnit.MILLISECONDS)) {
            try {
                LOGGER.debug("获得锁,开始执行任务。。。");
                task.run();
            } finally {
                lock.release();
                LOGGER.debug("释放锁,path:" + path);
            }
        } else {
            LOGGER.info("任务执行失败,在时间:" + getLockTimeout + "ms内,未获得分布式锁!");
        }
    } catch (Exception e) {
        LOGGER.error("执行分布式锁任务异常。", e);
    }

}
 
开发者ID:classtag,项目名称:scratch_zookeeper_netty,代码行数:29,代码来源:ZKClientImpl.java

示例13: supervene

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
public void supervene() {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final InterProcessLock interProcessLock = new InterProcessMutex(curatorFramework, "/lock");

    int count = 10;
    while (count > 0) {

        new Thread() {
            @Override
            public void run() {
                try {
                    countDownLatch.await();
                    interProcessLock.acquire();
                    String now = simpleDateFormat.format(new Date());
                    LOG.info("Now time: ".concat(now));
                    interProcessLock.release();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();
        count--;
    }
    countDownLatch.countDown();
}
 
开发者ID:asdf2014,项目名称:yuzhouwan,代码行数:26,代码来源:CuratorDistributedLock.java

示例14: testContention

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
@Test
public void testContention() throws Exception
{
    try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) )
    {
        client.start();

        InterProcessMutex lock1 = new InterProcessMutex(client, "/one/two");
        InterProcessMutex lock2 = new InterProcessMutex(client, "/one/two");
        CountDownLatch latch = new CountDownLatch(1);
        AsyncWrappers.lockAsync(lock1).thenAccept(__ -> {
            latch.countDown();  // don't release the lock
        });
        Assert.assertTrue(timing.awaitLatch(latch));

        CountDownLatch latch2 = new CountDownLatch(1);
        AsyncWrappers.lockAsync(lock2, timing.forSleepingABit().milliseconds(), TimeUnit.MILLISECONDS).exceptionally(e -> {
            if ( e instanceof AsyncWrappers.TimeoutException )
            {
                latch2.countDown();  // lock should still be held
            }
            return null;
        });
        Assert.assertTrue(timing.awaitLatch(latch2));
    }
}
 
开发者ID:apache,项目名称:curator,代码行数:27,代码来源:TestAsyncWrappers.java

示例15: LeaderSelector

import org.apache.curator.framework.recipes.locks.InterProcessMutex; //导入依赖的package包/类
/**
 * @param client          the client
 * @param leaderPath      the path for this leadership group
 * @param executorService thread pool to use
 * @param listener        listener
 */
public LeaderSelector(CuratorFramework client, String leaderPath, CloseableExecutorService executorService, LeaderSelectorListener listener)
{
    Preconditions.checkNotNull(client, "client cannot be null");
    PathUtils.validatePath(leaderPath);
    Preconditions.checkNotNull(listener, "listener cannot be null");

    this.client = client;
    this.listener = new WrappedListener(this, listener);
    hasLeadership = false;

    this.executorService = executorService;
    mutex = new InterProcessMutex(client, leaderPath)
    {
        @Override
        protected byte[] getLockNodeBytes()
        {
            return (id.length() > 0) ? getIdBytes(id) : null;
        }
    };
}
 
开发者ID:apache,项目名称:curator,代码行数:27,代码来源:LeaderSelector.java


注:本文中的org.apache.curator.framework.recipes.locks.InterProcessMutex类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。