drm.registerListener("HASingleton", listener);
drm.add("HASingleton", "HASingleton");
}
// Create a semaphore to gate the threads and acquire all its permits
Semaphore semaphore = new Semaphore(count + 1);
for (int i = 0; i <= count; i++)
semaphore.acquire();
DeployerThread[] deployers = new DeployerThread[keys.length];
for (int i = 0; i < count; i++)
{
DistributedReplicantManager.ReplicantListener listener = null;
if (conflicting)
{
listener = new MockHASingletonDeployer(deployer, keys[i], log);
}
else
{
listener = new NullListener();
}
deployers[i] = new DeployerThread(deployer, keys[i], listener, semaphore, log);
deployers[i].start();
}
String[] jgKeys = keys;
if (!conflicting)
{
// The JGroups thread also deals with the MockHASingletonDeployer
// key that the DeployerThreads don't
jgKeys = new String[keys.length + 1];
System.arraycopy(keys, 0, jgKeys, 0, keys.length);
jgKeys[keys.length] = "HASingleton";
}
JGroupsThread jgThread = new JGroupsThread(drm, jgKeys, remote.getName(), semaphore);
jgThread.start();
// Launch the threads
semaphore.release(count + 1);
boolean reacquired = false;
try
{
// Give the threads 5 secs to acquire the semaphore
long maxElapsed = System.currentTimeMillis() + 5000;
for (int i = 0; i < keys.length; i++)
{
if (deployers[i].getCount() < 0)
{
assertTrue("Thread " + keys[i] + " started in time",
maxElapsed - System.currentTimeMillis() > 0);
sleepThread(10);
i--; // try again
}
}
while (jgThread.getCount() < 0)
{
assertTrue("jgThread started in time",
maxElapsed - System.currentTimeMillis() > 0);
sleepThread(10);
}
// Reaquire all the permits, thus showing the threads didn't deadlock
// Give them 500 ms per loop
maxElapsed = System.currentTimeMillis() + (500 * LOOP_COUNT);
for (int i = 0; i <= count; i++)
{
long waitTime = maxElapsed - System.currentTimeMillis();
assertTrue("Acquired thread " + i, semaphore.attempt(waitTime));
}
reacquired = true;
// Ensure there were no exceptions