如何单元测试同步代码

时间:2010-05-13 09:28:25

标签: java unit-testing synchronization junit

我是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;
}

3 个答案:

答案 0 :(得分:4)

如果您不太关注使用JUnit,那么您可以使用TestNG框架。他们有多线程支持。

答案 1 :(得分:3)

作为测试框架的替代方法(或者在JUnit之上的额外扩展,如果你使用它)只是一些简单的旧代码:

  • 创建多个线程并将其应用于此例程。
  • 遍历各个主题并对每个主题进行测试,直到找到谁是领导者。
  • 将不同的环境变化(包括时间的推移)应用到程序的状态并重新进行测试。领导者仍然是领导者吗?
  • 现在,强迫领导者放弃(杀死那个线索或其他东西)。另一个线程接管了吗?

答案 2 :(得分:0)

对于JUnit,来自MultithreadingTesterjunit-toolbox