use of java.util.concurrent.Semaphore in project weave by continuuity.
the class ZKServiceDecoratorTest method testStateTransition.
@Test
public void testStateTransition() throws InterruptedException, ExecutionException, TimeoutException {
InMemoryZKServer zkServer = InMemoryZKServer.builder().build();
zkServer.startAndWait();
try {
final String namespace = Joiner.on('/').join("/weave", RunIds.generate(), "runnables", "Runner1");
final ZKClientService zkClient = ZKClientService.Builder.of(zkServer.getConnectionStr()).build();
zkClient.startAndWait();
zkClient.create(namespace, null, CreateMode.PERSISTENT).get();
try {
JsonObject content = new JsonObject();
content.addProperty("containerId", "container-123");
content.addProperty("host", "localhost");
RunId runId = RunIds.generate();
final Semaphore semaphore = new Semaphore(0);
ZKServiceDecorator service = new ZKServiceDecorator(ZKClients.namespace(zkClient, namespace), runId, Suppliers.ofInstance(content), new AbstractIdleService() {
@Override
protected void startUp() throws Exception {
Preconditions.checkArgument(semaphore.tryAcquire(5, TimeUnit.SECONDS), "Fail to start");
}
@Override
protected void shutDown() throws Exception {
Preconditions.checkArgument(semaphore.tryAcquire(5, TimeUnit.SECONDS), "Fail to stop");
}
});
final String runnablePath = namespace + "/" + runId.getId();
final AtomicReference<String> stateMatch = new AtomicReference<String>("STARTING");
watchDataChange(zkClient, runnablePath + "/state", semaphore, stateMatch);
Assert.assertEquals(Service.State.RUNNING, service.start().get(5, TimeUnit.SECONDS));
stateMatch.set("STOPPING");
Assert.assertEquals(Service.State.TERMINATED, service.stop().get(5, TimeUnit.SECONDS));
} finally {
zkClient.stopAndWait();
}
} finally {
zkServer.stopAndWait();
}
}
use of java.util.concurrent.Semaphore in project elasticsearch by elastic.
the class SearchServiceTests method testSearchWhileIndexDeleted.
public void testSearchWhileIndexDeleted() throws IOException, InterruptedException {
createIndex("index");
client().prepareIndex("index", "type", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
SearchService service = getInstanceFromNode(SearchService.class);
IndicesService indicesService = getInstanceFromNode(IndicesService.class);
IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index"));
IndexShard indexShard = indexService.getShard(0);
AtomicBoolean running = new AtomicBoolean(true);
CountDownLatch startGun = new CountDownLatch(1);
Semaphore semaphore = new Semaphore(Integer.MAX_VALUE);
final Thread thread = new Thread() {
@Override
public void run() {
startGun.countDown();
while (running.get()) {
service.afterIndexRemoved(indexService.index(), indexService.getIndexSettings(), DELETED);
if (randomBoolean()) {
// context in a non-sane way.
try {
semaphore.acquire();
} catch (InterruptedException e) {
throw new AssertionError(e);
}
client().prepareIndex("index", "type").setSource("field", "value").setRefreshPolicy(randomFrom(WriteRequest.RefreshPolicy.values())).execute(new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse indexResponse) {
semaphore.release();
}
@Override
public void onFailure(Exception e) {
semaphore.release();
}
});
}
}
}
};
thread.start();
startGun.await();
try {
final int rounds = scaledRandomIntBetween(100, 10000);
for (int i = 0; i < rounds; i++) {
try {
QuerySearchResultProvider querySearchResultProvider = service.executeQueryPhase(new ShardSearchLocalRequest(indexShard.shardId(), 1, SearchType.DEFAULT, new SearchSourceBuilder(), new String[0], false, new AliasFilter(null, Strings.EMPTY_ARRAY), 1.0f), new SearchTask(123L, "", "", "", null));
IntArrayList intCursors = new IntArrayList(1);
intCursors.add(0);
ShardFetchRequest req = new ShardFetchRequest(querySearchResultProvider.id(), intCursors, null);
service.executeFetchPhase(req, new SearchTask(123L, "", "", "", null));
} catch (AlreadyClosedException ex) {
throw ex;
} catch (IllegalStateException ex) {
assertEquals("search context is already closed can't increment refCount current count [0]", ex.getMessage());
} catch (SearchContextMissingException ex) {
// that's fine
}
}
} finally {
running.set(false);
thread.join();
semaphore.acquire(Integer.MAX_VALUE);
}
}
use of java.util.concurrent.Semaphore in project che by eclipse.
the class MavenTaskExecutor method waitForEndAllTasks.
public void waitForEndAllTasks() {
if (!isWorking) {
return;
}
Semaphore semaphore = new Semaphore(1);
try {
semaphore.acquire();
submitTask(semaphore::release);
while (true) {
if (!isWorking || semaphore.tryAcquire(1, TimeUnit.SECONDS)) {
return;
}
}
} catch (InterruptedException e) {
LOG.debug(e.getMessage(), e);
}
}
use of java.util.concurrent.Semaphore in project jetty.project by eclipse.
the class QoSFilter method init.
public void init(FilterConfig filterConfig) {
int max_priority = __DEFAULT_MAX_PRIORITY;
if (filterConfig.getInitParameter(MAX_PRIORITY_INIT_PARAM) != null)
max_priority = Integer.parseInt(filterConfig.getInitParameter(MAX_PRIORITY_INIT_PARAM));
_queues = new Queue[max_priority + 1];
_listeners = new AsyncListener[_queues.length];
for (int p = 0; p < _queues.length; ++p) {
_queues[p] = new ConcurrentLinkedQueue<>();
_listeners[p] = new QoSAsyncListener(p);
}
int maxRequests = __DEFAULT_PASSES;
if (filterConfig.getInitParameter(MAX_REQUESTS_INIT_PARAM) != null)
maxRequests = Integer.parseInt(filterConfig.getInitParameter(MAX_REQUESTS_INIT_PARAM));
_passes = new Semaphore(maxRequests, true);
_maxRequests = maxRequests;
long wait = __DEFAULT_WAIT_MS;
if (filterConfig.getInitParameter(MAX_WAIT_INIT_PARAM) != null)
wait = Integer.parseInt(filterConfig.getInitParameter(MAX_WAIT_INIT_PARAM));
_waitMs = wait;
long suspend = __DEFAULT_TIMEOUT_MS;
if (filterConfig.getInitParameter(SUSPEND_INIT_PARAM) != null)
suspend = Integer.parseInt(filterConfig.getInitParameter(SUSPEND_INIT_PARAM));
_suspendMs = suspend;
ServletContext context = filterConfig.getServletContext();
if (context != null && Boolean.parseBoolean(filterConfig.getInitParameter(MANAGED_ATTR_INIT_PARAM)))
context.setAttribute(filterConfig.getFilterName(), this);
}
use of java.util.concurrent.Semaphore in project jetty.project by eclipse.
the class QoSFilter method setMaxRequests.
/**
* Set the maximum number of requests allowed to be processed
* at the same time.
*
* @param value the number of requests
*/
public void setMaxRequests(int value) {
_passes = new Semaphore((value - getMaxRequests() + _passes.availablePermits()), true);
_maxRequests = value;
}
Aggregations