use of io.etcd.jetcd.Election in project jetcd by coreos.
the class ElectionTest method testSynchronizationBarrier.
@Test
public void testSynchronizationBarrier() throws Exception {
final int threadCount = 5;
final Random random = new Random();
ByteSequence electionName = ByteSequence.from(randomString(), StandardCharsets.UTF_8);
final AtomicInteger sharedVariable = new AtomicInteger(0);
// create separate clients so they will compete for access to shared resource
List<Client> clients = new ArrayList<>(threadCount);
List<Long> leases = new ArrayList<>(threadCount);
for (int i = 0; i < threadCount; ++i) {
Client client = TestUtil.client(cluster).build();
long leaseId = client.getLeaseClient().grant(100).get().getID();
clients.add(client);
leases.add(leaseId);
}
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
List<Future<?>> futures = new ArrayList<>(threadCount);
for (int i = 0; i < threadCount; ++i) {
final int id = i;
final ByteSequence proposal = ByteSequence.from(Integer.toString(id), StandardCharsets.UTF_8);
futures.add(executor.submit(() -> {
try {
Election electionClient = clients.get(id).getElectionClient();
CampaignResponse campaignResponse = electionClient.campaign(electionName, leases.get(id), proposal).get(OPERATION_TIMEOUT, TimeUnit.SECONDS);
int localCopy = sharedVariable.get();
Thread.sleep(200 + random.nextInt(300));
sharedVariable.set(localCopy + 1);
electionClient.resign(campaignResponse.getLeader()).get(OPERATION_TIMEOUT, TimeUnit.SECONDS);
} catch (Exception e) {
fail("Unexpected error in thread {}: {}", id, e);
}
}));
}
executor.shutdown();
executor.awaitTermination(threadCount * OPERATION_TIMEOUT, TimeUnit.SECONDS);
futures.forEach(f -> assertThat(f).isDone());
assertThat(sharedVariable.get()).isEqualTo(threadCount);
GetOption getOption = GetOption.newBuilder().isPrefix(true).build();
assertThat(kvClient.get(electionName, getOption).get().getCount()).isEqualTo(0L);
for (int i = 0; i < threadCount; ++i) {
clients.get(i).getLeaseClient().revoke(leases.get(i)).get();
clients.get(i).close();
}
}
use of io.etcd.jetcd.Election in project jetcd by coreos.
the class ElectionImpl method observe.
@Override
public void observe(ByteSequence electionName, Listener listener) {
checkNotNull(electionName, "election name should not be null");
checkNotNull(listener, "listener should not be null");
LeaderRequest request = LeaderRequest.newBuilder().setName(ByteString.copyFrom(electionName.getBytes())).build();
stub.observe(request).handler(value -> listener.onNext(new LeaderResponse(value, namespace))).endHandler(ignored -> listener.onCompleted()).exceptionHandler(error -> listener.onError(EtcdExceptionFactory.toEtcdException(error)));
}
Aggregations