如何对同步代码进行单元测试

2023-11-23

我是 Java 和 junit 的新手。我有以下一段代码想要测试。如果您能发送有关测试它的最佳方法的想法,我将不胜感激。

基本上,以下代码是关于从集群中选举领导者的。领导者持有共享缓存上的锁,如果领导者以某种方式失去了缓存上的锁,则领导者的服务将恢复并被释放。

我如何确保领导者/线程仍然持有缓存上的锁,并且当第一个线程正在执行时另一个线程无法恢复其服务?

public interface ContinuousService {

public void resume();
public void pause();
}


public abstract class ClusterServiceManager {
private volatile boolean leader = false;
private volatile boolean electable = true;
private List<ContinuousService> services;

protected synchronized void onElected() {
    if (!leader) {
        for (ContinuousService service : services) {
            service.resume();
        }
        leader = true;
    }
}

protected synchronized void onDeposed() {
    if (leader) {
        for (ContinuousService service : services) {
            service.pause();
        }
        leader = false;
    }
}

public void setServices(List<ContinuousService> services) {
    this.services = services;
}

@ManagedAttribute
public boolean isElectable() {
    return electable;
}

@ManagedAttribute
public boolean isLeader() {
    return leader;
}



public class TangosolLeaderElector extends ClusterServiceManager implements Runnable {
private static final Logger log = LoggerFactory.getLogger(TangosolLeaderElector.class);
private String election;
private long electionWaitTime= 5000L;

private NamedCache cache;

public void start() {
    log.info("Starting LeaderElector ({})",election);
    Thread t = new Thread(this, "LeaderElector ("+election+")");
    t.setDaemon(true);
    t.start();
}

public void run() {
    // Give the connection a chance to start itself up
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {}

    boolean wasElectable = !isElectable();
    while (true) {
        if (isElectable()) {
            if (!wasElectable) {
                log.info("Leadership requested on election: {}",election);
                wasElectable = isElectable();
            }
            boolean elected = false;
            try {
                // Try and get the lock on the LeaderElectorCache for the current election
                if (!cache.lock(election, electionWaitTime)) {
                    // We didn't get the lock. cycle round again. 
                    // This code to ensure we check the electable flag every now & then
                    continue;
                }
                elected = true;
                log.info("Leadership taken on election: {}",election);
                onElected();

                // Wait here until the services fail in some way.
                while (true) {
                    try {
                        Thread.sleep(electionWaitTime);
                    } catch (InterruptedException e) {}
                    if (!cache.lock(election, 0)) {
                        log.warn("Cache lock no longer held for election: {}", election);
                        break;
                    } else if (!isElectable()) {
                        log.warn("Node is no longer electable for election: {}", election);
                        break;
                    }
                    // We're fine - loop round and go back to sleep.
                }
            } catch (Exception e) {
                if (log.isErrorEnabled()) {
                    log.error("Leadership election " + election + " failed (try bfmq logs for details)", e);
                }
            } finally {
                if (elected) {
                    cache.unlock(election);
                    log.info("Leadership resigned on election: {}",election);
                    onDeposed();
                }
                // On deposition, do not try and get re-elected for at least the standard wait time.
                try { Thread.sleep(electionWaitTime); } catch (InterruptedException e) {}
            }
        } else {
            // Not electable - wait a bit and check again.
            if (wasElectable) {
                log.info("Leadership NOT requested on election ({}) - node not electable",election);
                wasElectable = isElectable();
            }
            try {
                Thread.sleep(electionWaitTime);
            } catch (InterruptedException e) {}
        }
    }
}

public void setElection(String election) {
    this.election = election;
}

@ManagedAttribute
public String getElection() {
    return election;
}

public void setNamedCache(NamedCache nc) {
    this.cache = nc;
}

如果你对使用 JUnit 不太讲究,那么你可以使用 TestNG 框架。他们有多线程支持。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何对同步代码进行单元测试 的相关文章

随机推荐

  • 将 LINQ to SQL 与 Oracle 结合使用[关闭]

    Closed 这个问题需要多问focused 目前不接受答案 我知道 linq to sql 实际上是 LINQ to SQL Server 我还读到 人们可以构建自己的 LINQ 提供程序 以便连接到其他数据库系统 如 oracle 或
  • Perl Parallel::ForkManager 与 DBI 数据库处理程序

    我对并行执行多个数据库操作感兴趣 我已经使用过 Perl Parallel ForkManager 但尚未将其用于任何数据库 我读过数据库连接是没有得到很好的支持有了这个 有人对此有经验吗 作为一个例子 我可能会生成一个系统调用 它执行 D
  • Traefik Dashboard:Ingress 和 IngressRoute,它们可以共存吗?

    最近我正在将一个项目迁移到 Kubernetes 并使用 Traefik 作为入口控制器 对于 Traefik 我使用 Traefik Ku bernetes Ingress 提供程序进行路由 当我尝试添加 Traefik 仪表板时 我发现
  • 多个键范围作为 CouchDB 视图的参数

    根本问题 假设我的文档有 类别 and 时间戳 如果我想要所有文件 foo 时间戳在过去两个小时内的类别 很简单 function doc emit doc category doc timestamp null 然后查询为 GET ser
  • GWT 服务异常日志记录的最佳实践

    我决定将日志系统添加到我的 gwt 服务层 首先 我想记录从该层引发的所有异常 我有一个类似于Spring的ServletDispatcher的对象 它调用其他服务 我以为我可以在那里添加日志记录 但我意识到 GWT 服务将已检查的异常包装
  • CSS边距恐怖;边距在父元素外部添加空间[重复]

    这个问题在这里已经有答案了 我的 CSS 边距没有按照我想要或期望的方式运行 我似乎我的标题 margin top 影响了它周围的 div 标签 This is what I want and expect but this is what
  • 更新 matplotlib 中的行

    我有一个包含多个数据集的图表 随着数据的更新 我需要不断地重新绘制这些线 每条线都是单独的 如何重复删除并重新建立它 最好不必每次都删除整个图表并重新绘制其上的所有线条 usr bin env python import time from
  • 我可以使用 jquery 确定设备处于纵向还是横向模式吗?

    我想有条件地改变用户在我要创建的照片库网站上看到的内容 具体取决于用于查看该网站的设备是否处于纵向 垂直与横向 水平模式 方向 这可能吗 Try the orientationchange事件处理程序 如下所示 window bind or
  • 从 MySQL 中的字段中选择最常见的值

    我有一个包含一百万行的表 如何从字段中选择最常见的 表中出现最多的值 值 您需要按感兴趣的列进行分组 并为每个值选择该值本身及其出现的行数 然后就是排序 将最常见的值放在第一位 并将结果限制为一行的问题 以查询形式 SELECT colum
  • 如何更改 GGally::ggpairs 的调色板?

    这与中的问题相同R 和 ggpairs 中用户定义的调色板 or 有没有办法使用 ggplot 更改 GGally ggpairs 的调色板 只是那里的解决方案不再有效 我也想改变调色板 但是有没有办法使用 ggplot 更改 GGally
  • Python:确定序列中的任何项目是否等于任何其他项目

    我想比较多个对象并返回True仅当所有对象之间不相等时 我尝试使用下面的代码 但它不起作用 如果 obj1 和 obj3 相等且 obj2 和 obj3 不相等 则结果为True obj1 obj2 obj3 我有超过 3 个对象需要比较
  • Centos 6.4 - 无法从共享对象映射段:权限被拒绝

    您好 我正在尝试安装 Phusion Passenger 安装成功 但执行时出现以下错误service httpd start Starting httpd httpd Syntax error on line 221 of etc htt
  • 具有多个参数的 MVC4 Web API Rest 接口

    我有一个名为 LoginController 的控制器 其 Get 方法的签名为 public string Get string Key string Code string UserID string Password 我希望能够通过类
  • Github Actions 有模板吗

    由于我的 Github Actions 中有重复的步骤 我想创建一个模板 让我们举个例子 name ci on push jobs build and test strategy matrix os ubuntu latest runs o
  • 如何多次使用相同的参数?

    我知道关于sprintf 但是如何多次使用相同的参数呢 如果我使用以下代码 则会收到有关使用少量参数的错误 sprintf blabla s 11111 s test 我想更换 s with test twice Use the 编号占位符
  • Javascript 排序“不稳定” - 我该如何解决这个问题?

    根据MDN spec Javascript sort 函数 不稳定 不维护相同元素的输入顺序 讽刺的是 Firefox 目前似乎还没有实现这一点 但 Chrome 似乎实现了 这给我留下了一些问题 我有一组元素要排序 一旦排序 我想将它们标
  • 如何将 3 个 UIButtons 对齐到 UITableCellView 的中心?

    我怎样才能对齐3UIButtons 到 a 的中心UITableCellView 例如说我有 3UIButtons 的标题 Email Phone Skype 其中一项或多项是可能的UIButtons 被隐藏 例如 如果电话UIButton
  • 基于 Zend_Framework 的应用程序示例 [已关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心以获得指导 您知道有哪些基于 Zend
  • Python 中的对象引用是什么?

    一本Python入门教科书对 对象引用 的定义如下 但我不明白 对象引用只不过是对象身份 存储对象的内存地址 的具体表示 教科书尝试通过使用箭头将对象引用显示为来自变量的某种关系来说明这一点a到一个物体1234在赋值语句中a 1234 从我
  • 如何对同步代码进行单元测试

    我是 Java 和 junit 的新手 我有以下一段代码想要测试 如果您能发送有关测试它的最佳方法的想法 我将不胜感激 基本上 以下代码是关于从集群中选举领导者的 领导者持有共享缓存上的锁 如果领导者以某种方式失去了缓存上的锁 则领导者的服