Example usage for java.util.concurrent Semaphore Semaphore

List of usage examples for java.util.concurrent Semaphore Semaphore

Introduction

In this page you can find the example usage for java.util.concurrent Semaphore Semaphore.

Prototype

public Semaphore(int permits) 

Source Link

Document

Creates a Semaphore with the given number of permits and nonfair fairness setting.

Usage

From source file:com.qwazr.search.index.SchemaInstance.java

private synchronized void checkSettings() throws IOException, URISyntaxException {
    if (settingsDefinition == null) {
        readSemaphore = null;//from  w  w w.  ja  v a 2  s. c om
        writeSemaphore = null;
        return;
    }
    if (settingsDefinition.max_simultaneous_read != null)
        readSemaphore = new Semaphore(settingsDefinition.max_simultaneous_read);
    else
        readSemaphore = null;
    if (settingsDefinition.max_simultaneous_write != null)
        writeSemaphore = new Semaphore(settingsDefinition.max_simultaneous_write);
    else
        writeSemaphore = null;
}

From source file:gobblin.runtime.job_catalog.FSJobCatalogHelperTest.java

@Test(dependsOnMethods = { "testloadGenericJobConfig" })
public void testPathAlterationObserver() throws Exception {
    PathAlterationObserverScheduler detector = new PathAlterationObserverScheduler(1000);
    final Set<Path> fileAltered = Sets.newHashSet();
    final Semaphore semaphore = new Semaphore(0);
    PathAlterationListener listener = new PathAlterationListenerAdaptor() {

        @Override/*from   w  w  w .ja v a2 s  .c  om*/
        public void onFileCreate(Path path) {
            fileAltered.add(path);
            semaphore.release();
        }

        @Override
        public void onFileChange(Path path) {
            fileAltered.add(path);
            semaphore.release();
        }
    };

    detector.addPathAlterationObserver(listener, Optional.<PathAlterationObserver>absent(),
            new Path(this.jobConfigDir.getPath()));
    try {
        detector.start();
        // Give the monitor some time to start
        Thread.sleep(1000);

        File jobConfigFile = new File(this.subDir11, "test111.pull");
        Files.touch(jobConfigFile);

        File newJobConfigFile = new File(this.subDir11, "test112.pull");
        Files.append("k1=v1", newJobConfigFile, ConfigurationKeys.DEFAULT_CHARSET_ENCODING);

        semaphore.acquire(2);
        Assert.assertEquals(fileAltered.size(), 2);

        Assert.assertTrue(fileAltered.contains(new Path("file:" + jobConfigFile)));
        Assert.assertTrue(fileAltered.contains(new Path("file:" + newJobConfigFile)));
    } finally {
        detector.stop();
    }
}

From source file:org.apache.giraph.comm.flow_control.CreditBasedFlowControl.java

/**
 * Constructor/* w  w w.ja va2s  . co  m*/
 * @param conf configuration
 * @param nettyClient netty client
 */
public CreditBasedFlowControl(ImmutableClassesGiraphConfiguration conf, NettyClient nettyClient) {
    this.nettyClient = nettyClient;
    maxOpenRequestsPerWorker = (short) MAX_NUM_OF_OPEN_REQUESTS_PER_WORKER.get(conf);
    checkState(maxOpenRequestsPerWorker < 0x4000 && maxOpenRequestsPerWorker > 0,
            "NettyClient: max number of open " + "requests should be in range (0, " + 0x4FFF + ")");
    unsentRequestPermit = new Semaphore(MAX_NUM_OF_UNSENT_REQUESTS.get(conf));
    unsentWaitMsecs = UNSENT_CACHE_WAIT_INTERVAL.get(conf);
    waitingRequestMsecs = WAITING_REQUEST_MSECS.get(conf);
    shouldTerminate = false;
    CallableFactory<Void> callableFactory = new CallableFactory<Void>() {
        @Override
        public Callable<Void> newCallable(int callableId) {
            return new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    while (true) {
                        synchronized (workersToResume) {
                            if (shouldTerminate) {
                                break;
                            }
                            for (Integer workerId : workersToResume) {
                                if (maxOpenRequestsPerWorker != 0) {
                                    sendResumeSignal(workerId);
                                } else {
                                    break;
                                }
                            }
                            try {
                                workersToResume.wait();
                            } catch (InterruptedException e) {
                                throw new IllegalStateException("call: caught exception "
                                        + "while waiting for resume-sender thread to be notified!", e);
                            }
                        }
                    }
                    return null;
                }
            };
        }
    };

    ExecutorService executor = Executors
            .newSingleThreadExecutor(ThreadUtils.createThreadFactory("resume-sender"));
    resumeThreadResult = executor.submit(new LogStacktraceCallable<>(callableFactory.newCallable(0)));
    executor.shutdown();
}

From source file:org.openconcerto.erp.model.EditionFichePayeModel.java

/**
 * Validation des fiches selectionnes/*ww w. j  a v a 2  s.  c  om*/
 * 
 * @param annee
 * @param idMois
 * @param du
 * @param au
 */
public void validationFiche(final String annee, final int idMois, final Date du, final Date au) {

    final Thread t = new Thread() {
        @Override
        public void run() {
            try {
                EditionFichePayeModel.this.bar.setMaximum(EditionFichePayeModel.this.vData.size() * 4 - 1);
                EditionFichePayeModel.this.bar.setString(null);
                EditionFichePayeModel.this.bar.setStringPainted(false);
                int tmp = 0;
                EditionFichePayeModel.this.bar.setValue(tmp);

                final SQLElement eltSal = Configuration.getInstance().getDirectory().getElement("SALARIE");
                final SQLElement eltFichePaye = Configuration.getInstance().getDirectory()
                        .getElement("FICHE_PAYE");

                // On cre la fiche de paye pour chacun des salaris slectionns
                for (int i = 0; i < EditionFichePayeModel.this.vData.size(); i++) {
                    Map<String, Object> m = EditionFichePayeModel.this.vData.get(i);
                    Boolean bCreate = (Boolean) m.get("A_CREER");

                    if (bCreate.booleanValue()) {
                        final int idSal = ((Number) m.get("ID_SALARIE")).intValue();
                        SQLRow rowSalarie = eltSal.getTable().getRow(idSal);
                        final String salName = rowSalarie.getString("CODE") + " " + rowSalarie.getString("NOM");
                        final SQLRow row = eltSal.getTable().getRow(idSal);
                        final int idFiche = row.getInt("ID_FICHE_PAYE");

                        // Update de la periode
                        SQLRowValues rowVals = new SQLRowValues(eltFichePaye.getTable());
                        rowVals.put("ANNEE", Integer.valueOf(annee));
                        rowVals.put("ID_MOIS", idMois);
                        rowVals.put("DU", du);
                        rowVals.put("AU", au);
                        try {
                            rowVals.update(idFiche);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                EditionFichePayeModel.this.labelEtat
                                        .setText(salName + " - Mise  jour de la priode");
                            }
                        });
                        EditionFichePayeModel.this.bar.setValue(tmp++);

                        // Visualisation
                        Boolean bVisu = (Boolean) m.get("VISU");
                        boolean resume = true;
                        if (bVisu.booleanValue()) {

                            final Semaphore semaphore = new Semaphore(1);
                            try {
                                semaphore.acquire();
                                // on demande le smaphore

                                final VisualisationPayeFrame frame = new VisualisationPayeFrame(semaphore);
                                SwingUtilities.invokeLater(new Runnable() {
                                    public void run() {

                                        frame.pack();
                                        frame.setSelectedFichePaye(idFiche);
                                        frame.setVisible(true);
                                    }
                                });

                                // synchronized (this) {
                                // try {
                                // System.err.println("Wait ");
                                // this.wait();
                                // System.err.println("WakeUp");
                                //
                                // } catch (InterruptedException e) {
                                // e.printStackTrace();
                                // }
                                // }
                                semaphore.acquire();
                                System.err.println("Etat --> " + frame.getAnswer());
                                resume = frame.getAnswer();
                            } catch (InterruptedException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                        }

                        EditionFichePayeModel.this.bar.setValue(tmp++);

                        // test si l'utilisateur n'a pas annul l'action
                        if (resume) {
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    EditionFichePayeModel.this.labelEtat
                                            .setText(salName + " - Validation de la fiche");
                                }
                            });
                            // Validation de la fiche
                            FichePayeSQLElement.validationFiche(idFiche);

                            // Update des rubriques
                            SQLRow rowSalNew = eltSal.getTable().getRow(idSal);
                            final int idFicheNew = rowSalNew.getInt("ID_FICHE_PAYE");
                            FichePayeModel ficheModel = new FichePayeModel(idFicheNew);
                            ficheModel.loadAllElements();

                            EditionFichePayeModel.this.bar.setValue(tmp++);

                            // Impression
                            Boolean bPrint = (Boolean) m.get("IMPRESSION");
                            if (bPrint.booleanValue()) {
                                SQLRow rowFiche = eltFichePaye.getTable().getRow(idFiche);
                                FichePayeSheet.generation(rowFiche, false);
                                FichePayeSheet.impression(rowFiche);
                            }

                            EditionFichePayeModel.this.bar.setValue(tmp++);

                        } else {

                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    EditionFichePayeModel.this.labelEtat
                                            .setText(salName + " - Cration annule");
                                }
                            });
                            tmp += 2;
                            EditionFichePayeModel.this.bar.setValue(tmp);

                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    String msg = "Cration annule pour " + row.getString("CODE") + " "
                                            + row.getString("NOM") + " " + row.getString("PRENOM");
                                    JOptionPane.showMessageDialog(null, msg, "Cration des payes",
                                            JOptionPane.INFORMATION_MESSAGE);
                                }
                            });
                        }
                    } else {

                        tmp += 4;
                        EditionFichePayeModel.this.bar.setValue(tmp);

                    }
                }
            } catch (Exception e) {
                ExceptionHandler.handle("Erreur pendant la cration des fiches de paye", e);
            }
            // Fin de l'edition
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    updateAll();
                    JOptionPane.showMessageDialog(null, "Cration des payes termine", "Cration paye",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            });
            EditionFichePayeModel.this.labelEtat.setText("Traitement termin");
            EditionFichePayeModel.this.bar.setString("Termin");
            EditionFichePayeModel.this.bar.setStringPainted(true);
        }
    };
    t.start();
}

From source file:org.apache.gobblin.runtime.job_catalog.FSJobCatalogHelperTest.java

@Test(enabled = false, dependsOnMethods = { "testloadGenericJobConfig" })
public void testPathAlterationObserver() throws Exception {
    PathAlterationObserverScheduler detector = new PathAlterationObserverScheduler(1000);
    final Set<Path> fileAltered = Sets.newHashSet();
    final Semaphore semaphore = new Semaphore(0);
    PathAlterationListener listener = new PathAlterationListenerAdaptor() {

        @Override/*  ww w. j  a va 2 s  . co m*/
        public void onFileCreate(Path path) {
            fileAltered.add(path);
            semaphore.release();
        }

        @Override
        public void onFileChange(Path path) {
            fileAltered.add(path);
            semaphore.release();
        }
    };

    detector.addPathAlterationObserver(listener, Optional.<PathAlterationObserver>absent(),
            new Path(this.jobConfigDir.getPath()));
    try {
        detector.start();
        // Give the monitor some time to start
        Thread.sleep(1000);

        File jobConfigFile = new File(this.subDir11, "test111.pull");
        Files.touch(jobConfigFile);

        File newJobConfigFile = new File(this.subDir11, "test112.pull");
        Files.append("k1=v1", newJobConfigFile, ConfigurationKeys.DEFAULT_CHARSET_ENCODING);

        semaphore.acquire(2);
        Assert.assertEquals(fileAltered.size(), 2);

        Assert.assertTrue(fileAltered.contains(new Path("file:" + jobConfigFile)));
        Assert.assertTrue(fileAltered.contains(new Path("file:" + newJobConfigFile)));
    } finally {
        detector.stop();
    }
}

From source file:org.paxle.data.db.impl.CommandDBTest.java

public void _testVeryLargeURLSet() throws MalformedURLException, InterruptedException {
    final int MAX = 1000000;
    final int chunkSize = 1000;

    System.setProperty("derby.storage.pageCacheSize", "2000"); // default 1000
    //System.setProperty("derby.storage.pageSize", "32768");      // default 4096 bytes

    // setup DB//from  w  w w  . ja  va2 s .  co m
    // this.setupDB(POSTGRESQL_CONFIG_FILE, String.format(POSTGRESQL_CONNECTION_URL,"192.168.10.201"));
    //this.setupDB(H2_CONFIG_FILE, H2_CONNECTION_URL, "sa", "");
    this.setupDB(DERBY_CONFIG_FILE, DERBY_CONNECTION_URL, null, null);

    // command-tracker must be called MAX times
    checking(new Expectations() {
        {
            exactly(MAX).of(cmdTracker).commandCreated(with(equal("org.paxle.data.db.ICommandDB")),
                    with(any(ICommand.class)));
        }
    });

    final Semaphore s = new Semaphore(-MAX + 1);

    new Thread() {
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }

            // create a dummy data-sink
            cmdDB.setDataSink(new DummyDataSink(s));
        };
    }.start();

    // store new commands
    long start = System.currentTimeMillis();

    LinkedList<URI> testURI = new LinkedList<URI>();
    for (int i = 1; i <= MAX; i++) {
        URI nextCommand = URI.create("http://test.paxle.net/" + i);
        testURI.add(nextCommand);

        if (i % chunkSize == 0 || i == MAX) {
            int known = this.cmdDB.storeUnknownLocations(0, 1, testURI);
            assertEquals(0, known);
            testURI.clear();
        }
    }

    // wait for all commands to be enqueued
    s.acquire();

    System.out.println(String.format("Storing and loading %d URL took %d ms", Integer.valueOf(MAX),
            Long.valueOf(System.currentTimeMillis() - start)));
}

From source file:com.parse.ParsePushTest.java

@Test
public void testSubscribeInBackgroundWithCallbackSuccess() throws Exception {
    final ParsePushChannelsController controller = mock(ParsePushChannelsController.class);
    when(controller.subscribeInBackground(anyString())).thenReturn(Task.<Void>forResult(null));
    ParseCorePlugins.getInstance().registerPushChannelsController(controller);

    ParsePush push = new ParsePush();
    final Semaphore done = new Semaphore(0);
    final Capture<Exception> exceptionCapture = new Capture<>();
    push.subscribeInBackground("test", new SaveCallback() {
        @Override/* w w w  . j av a 2s  .c o  m*/
        public void done(ParseException e) {
            exceptionCapture.set(e);
            done.release();
        }
    });
    assertNull(exceptionCapture.get());
    assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
    verify(controller, times(1)).subscribeInBackground("test");
}

From source file:com.parse.ParseOkHttpClientTest.java

private void testParseOkHttpClientExecuteWithInterceptor(boolean isInternalInterceptorTest) throws Exception {
    // Start mock server
    server.enqueue(generateServerResponse());
    server.start();/* w w  w.j a v a  2  s .  c om*/

    ParseHttpClient client = new ParseOkHttpClient(10000, null);

    // Make ParseHttpRequest
    ParseHttpRequest parseRequest = generateClientRequest();

    final Semaphore done = new Semaphore(0);
    ParseNetworkInterceptor interceptor = new ParseNetworkInterceptor() {
        @Override
        public ParseHttpResponse intercept(Chain chain) throws IOException {
            done.release();

            ParseHttpRequest request = chain.getRequest();

            // Verify original request
            verifyClientRequest(request);

            // Change request
            ParseHttpRequest requestAgain = generateInterceptorRequest();

            // Proceed
            ParseHttpResponse parseResponse = chain.proceed(requestAgain);

            // Verify original response
            verifyServerResponse(parseResponse);

            // Change response
            return generateInterceptorResponse();
        }
    };

    // Add interceptor
    if (isInternalInterceptorTest) {
        client.addInternalInterceptor(interceptor);
    } else {
        client.addExternalInterceptor(interceptor);
    }

    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);

    // Make sure interceptor is called
    assertTrue(done.tryAcquire(5, TimeUnit.SECONDS));

    RecordedRequest recordedRequest = server.takeRequest();
    // Verify request changed by interceptor
    verifyInterceptorRequest(recordedRequest);

    // Verify response changed by interceptor
    verifyInterceptorResponse(parseResponse);
}

From source file:org.openengsb.opencit.core.projectmanager.internal.ProjectManagerImplTest.java

@Test
@SuppressWarnings("unchecked")
public void build_shouldSuspendPoller() throws Exception {
    List<CommitRef> fakeCommits = new LinkedList<CommitRef>();
    fakeCommits.add(Mockito.mock(CommitRef.class));

    final Semaphore eventSync = new Semaphore(0);
    when(workflowService.startFlow(eq("ci"), any(Map.class))).thenReturn(1L);
    doAnswer(new Answer<Void>() {
        @Override/*w  w  w. j  a  va  2  s. co  m*/
        public Void answer(InvocationOnMock invocation) throws Throwable {
            eventSync.acquire();
            return null;
        }
    }).when(workflowService).waitForFlowToFinish(eq(1L), anyLong());
    when(scmMock.update()).thenReturn(fakeCommits, (List<CommitRef>[]) null);

    scheduler.setPollInterval(100L);

    Project project = new Project("test");
    project.setState(State.OK);
    projectManager.createProject(project);
    Thread.sleep(200);
    assertThat(scheduler.isProjectBuilding("test"), is(true));
    Thread.sleep(200);

    verify(scmMock).update();

    eventSync.release();

    Thread.sleep(200);

    assertThat(scheduler.isProjectBuilding("test"), is(false));
    assertThat(scheduler.isProjectPolling("test"), is(true));
}

From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testNoUnits() throws InterruptedException {
    _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> {
        // Annotations
        Assert.assertEquals(0, r.getAnnotationsCount());

        // Dimensions
        Assert.assertEquals(0, r.getDimensionsCount());

        // Samples
        assertSample(r.getTimersList(), "timer", 7d);
        assertSample(r.getCountersList(), "counter", 8d);
        assertSample(r.getGaugesList(), "gauge", 9d);
    })).willReturn(WireMock.aResponse().withStatus(200)));

    final Semaphore semaphore = new Semaphore(0);
    final Sink sink = new ApacheHttpSink.Builder()
            .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH))
            .setEventHandler(new CompletionHandler(semaphore)).build();

    final TsdEvent event = new TsdEvent(Collections.emptyMap(),
            createQuantityMap("timer", TsdQuantity.newInstance(7d, null)),
            createQuantityMap("counter", TsdQuantity.newInstance(8d, null)),
            createQuantityMap("gauge", TsdQuantity.newInstance(9d, null)));

    sink.record(event);/*from  w w  w  .  j  a va 2 s . c o m*/
    semaphore.acquire();

    // Request matcher
    final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH))
            .withHeader("Content-Type", WireMock.equalTo("application/octet-stream"));

    // Assert that data was sent
    _wireMockRule.verify(1, requestPattern);
    Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty());
}