java轮训算法_java 平滑加权轮询算法实现与讲解

public classRobinExecute {/**线程使用完不会清除该变量,会一直保留着,由于线程 池化所以不用担心内存泄漏 **/

private ThreadLocal weightRoundRobinTl = new ThreadLocal();private ReentrantLock lock = newReentrantLock();/**为什么添加volatile,是因为 ReentrantLock 并不保证内存可见性 **/

private volatileSmoothWeightRoundRobin smoothWeightRoundRobin;public static voidmain(String[] args) {

RobinExecute robinExecute= newRobinExecute();/**================== TheadLocal ========================**/robinExecute.acquireWeightRoundRobinOfTheadLocal().getServer();/**================== ReentrantLock 可重入锁 ========================**/robinExecute.getLock().lock();//notice: 注意此锁会无休止的等待资源,如果使用此锁,无比保证资源能够被拿到

try{

robinExecute.acquireWeightRoundRobinOfLock();

}catch(Exception e) {

e.printStackTrace();

}finally { //确保一定要释放锁

robinExecute.getLock().unlock();

}

}/*** 在分布式情况,第二种使用方式 使用cas ReentrantLock 可重入锁

* notice:

*@return

*/

publicSmoothServer acquireWeightRoundRobinOfLock() {if (smoothWeightRoundRobin == null) {

SmoothWeightRoundRobin weightRoundRobin= newSmoothWeightRoundRobin();

List servers = new ArrayList<>();

servers.add(new SmoothServer("191", 1, 0));

servers.add(new SmoothServer("192", 2, 0));

servers.add(new SmoothServer("194", 4, 0));

weightRoundRobin.init(servers);

smoothWeightRoundRobin=weightRoundRobin;

}returnsmoothWeightRoundRobin.getServer();

}/*** 在分布式情况,第一种使用方式 ThreadLock

* notice: 只有在使用池化技术的情况才建议使用此方式,否则达不到效果,还会造成内存泄漏

*@return

*/

publicSmoothWeightRoundRobin acquireWeightRoundRobinOfTheadLocal() {returnOptional.ofNullable(weightRoundRobinTl.get())

.orElseGet(()->{

SmoothWeightRoundRobin weightRoundRobin= newSmoothWeightRoundRobin();

List servers = new ArrayList<>();

servers.add(new SmoothServer("191", 1, 0));

servers.add(new SmoothServer("192", 2, 0));

servers.add(new SmoothServer("194", 4, 0));

weightRoundRobin.init(servers);

weightRoundRobinTl.set(weightRoundRobin);returnweightRoundRobin;

});

}publicReentrantLock getLock() {returnlock;

}public ThreadLocalgetWeightRoundRobinTl() {returnweightRoundRobinTl;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值