本文整理汇总了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();
}
示例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;
}
}
示例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:
}
}
示例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);
}
}
示例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;
}
}
示例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:
}
}
示例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();
}
}
示例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();
}
示例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));
}
示例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);
}
示例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);
}
示例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);
}
}
示例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();
}
示例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));
}
}
示例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;
}
};
}