Java shared data_vertx里的SharedData解析1

vertx里一共可以引用两种sharedData

一种是package io.vertx.core.shareddata;

一种是package io.vertx.rxjava.core.shareddata;

首先看SharedData core下面的

项目中使用到了sharedData.getLockWithTimeout(,,)

sharedData.getLockWithTimeout

void getLocalLockWithTimeout(String name,

long timeout,

Handler> resultHandler)

其中实现类只有一个

@Override

public void getLockWithTimeout(String name, long timeout, Handler> resultHandler) {

Objects.requireNonNull(name, "name");

Objects.requireNonNull(resultHandler, "resultHandler");

Arguments.require(timeout >= 0, "timeout must be >= 0");

if (clusterManager == null) {

getLocalLockWithTimeout(name, timeout, resultHandler);

} else {

clusterManager.getLockWithTimeout(name, timeout, resultHandler);

}

}

这里是进行了判空,以及参数判定

有一个clusterManager是集群模式的判定

public class SharedDataImpl implements SharedData {

private static final long DEFAULT_LOCK_TIMEOUT = 10 * 1000;

private final VertxInternal vertx;

private final ClusterManager clusterManager;

private final LocalAsyncLocks localAsyncLocks;

private final ConcurrentMap> localAsyncMaps = new ConcurrentHashMap<>();

private final ConcurrentMap localCounters = new ConcurrentHashMap<>();

private final ConcurrentMap> localMaps = new ConcurrentHashMap<>();

public SharedDataImpl(VertxInternal vertx, ClusterManager clusterManager) {

this.vertx = vertx;

this.clusterManager = clusterManager;

localAsyncLocks = new LocalAsyncLocks();

}

在ClusterManager下面也有一个boolean来判定是否开启了集群管理器

/**

* Is the cluster manager active?

*

* @return true if active, false otherwise

*/

boolean isActive();

集群的话从集群中获取

if (clusterManager == null) {

getLocalLockWithTimeout(name, timeout, resultHandler);

} else {

clusterManager.getLockWithTimeout(name, timeout, resultHandler);

}

public void acquire(Context context, String name, long timeout, Handler> handler) {

LockWaiter lockWaiter = new LockWaiter(context, name, timeout, handler);

List waiters = waitersMap.compute(name, (s, list) -> {

List result;

if (list != null) {

result = new ArrayList<>(list.size() + 1);

result.addAll(list);

} else {

result = new ArrayList<>(1);

}

result.add(lockWaiter);

return result;

});

if (waiters.size() == 1) {

waiters.get(0).acquireLock();

}

}

LockWaiter(Context context, String lockName, long timeout, Handler> handler) {

this.context = context;

this.lockName = lockName;

this.handler = handler;

status = new AtomicReference<>(Status.WAITING);

timerId = timeout != Long.MAX_VALUE ? context.owner().setTimer(timeout, tid -> timeout()) : null;

}

可以看到timerId是通过setTimer来最终实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值