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:org.kuali.mobility.icons.service.IconsServiceImpl.java

/**
 * Creates the required file on the filesystem
 *
 * @param file File to write too/*from w  ww .j av a 2s.c o  m*/
 * @param icon WebIcon that we need to create a file of
 * @return size The size of the icon (this size must have the multiplier applied already)
 */
private File createFile(final File file, WebIcon icon, int size) {
    Semaphore oneToAdd = new Semaphore(1);
    /*
     * If there currently is a semaphore for the filename, the existing sema will be returned,
     * else the new semaphore will be added and return null (because there is no old value)
     */
    Semaphore sema = lockingMap.putIfAbsent(file.getName(), oneToAdd);
    if (sema == null) {
        sema = oneToAdd;
    }
    try {

        sema.acquire(); // Second concurrent user will wait here
        if (imageFileExists(file)) {
            return file;
        }
        file.createNewFile();

        Resource iconResource = applicationContext.getResource(icon.getPath());
        PNGTranscoder t = new PNGTranscoder();
        t.addTranscodingHint(PNGTranscoder.KEY_MAX_HEIGHT, new Float(size));
        t.addTranscodingHint(PNGTranscoder.KEY_MAX_WIDTH, new Float(size));
        t.addTranscodingHint(PNGTranscoder.KEY_BACKGROUND_COLOR, new Color(0, 0, 0, 0));
        OutputStream ostream = new FileOutputStream(file);

        // Create the transcoder input.
        TranscoderInput input = new TranscoderInput(iconResource.getInputStream());

        // Create the transcoder output.
        TranscoderOutput output = new TranscoderOutput(ostream);

        // Save the image.
        t.transcode(input, output);

        // Flush and close the stream.
        ostream.flush();
        ostream.close();
    } catch (Exception ex) {
        LOG.warn("Exception while creating file", ex);
        if (file.exists()) {
            file.delete();
        }
    } finally {
        sema.release();
    }
    return file;
}

From source file:com.impetus.ankush2.ganglia.GangliaDeployer.java

@Override
public boolean register(final ClusterConfig conf) {

    try {/*from  ww  w.  j a v  a2s  .  com*/
        if (String.valueOf(advanceConf.get(Constant.Keys.REGISTER_LEVEL))
                .equalsIgnoreCase(Constant.RegisterLevel.LEVEL1.toString())) {
            return true;
        }
        final String infoMsg = "Registering " + getComponentName() + "...";
        logger.info(infoMsg);
        // Getting node map for cluster deployment
        Map<String, Map<String, Object>> nodeMap = new HashMap<String, Map<String, Object>>(
                compConfig.getNodes());

        // Node Registration process ...
        final Semaphore semaphore = new Semaphore(nodeMap.size());
        for (final String host : nodeMap.keySet()) {
            semaphore.acquire();
            AppStoreWrapper.getExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    conf.getNodes().get(host).setStatus(configureServiceMonitoring(host));
                    if (semaphore != null) {
                        semaphore.release();
                    }
                }
            });
        }
        semaphore.acquire(nodeMap.size());

        // Return false if any of the node is not deployed.
        return AnkushUtils.getStatus(conf.getNodes());
    } catch (Exception e) {
        addClusterError("Could not register " + getComponentName(), e);
        return false;
    }
}

From source file:gobblin.util.SchedulerUtilsTest.java

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

        @Override//w w w .  j  av  a2  s  . co m
        public void onFileCreate(Path path) {
            fileAltered.add(path);
            semaphore.release();
        }

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

    SchedulerUtils.addPathAlterationObserver(monitor, listener, new Path(this.jobConfigDir.getPath()));
    try {
        monitor.start();
        // Give the monitor some time to start
        Thread.sleep(1000);

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

        File commonPropsFile = new File(this.subDir1, "test.properties");
        Files.touch(commonPropsFile);

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

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

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

From source file:org.springframework.batch.core.step.tasklet.TaskletStep.java

/**
 * Extension point mainly for test purposes so that the behaviour of the
 * lock can be manipulated to simulate various pathologies.
 *
 * @return a semaphore for locking access to the JobRepository
 *//*from w w w  . j  a va  2  s  .  c o m*/
protected Semaphore createSemaphore() {
    return new Semaphore(1);
}

From source file:org.mahasen.node.MahasenNodeManager.java

/**
 * @param myContent/*from  w  w w.  j a va2  s  . com*/
 */
public void insertPastContent(MahasenPropertyPastContent myContent) {

    //  String result = this.lookupDHT(resourceId);
    final Semaphore control = new Semaphore(0);

    mahasenPastTreeApp.insert(myContent, new Continuation<Boolean[], Exception>() {
        // the result is an Array of Booleans for each insert
        public void receiveResult(Boolean[] results) {

            int numSuccessfulStores = 0;

            for (int ctr = 0; ctr < results.length; ctr++) {
                if (results[ctr].booleanValue())
                    numSuccessfulStores++;
            }

            control.release();

            System.out.println(" PropertyTree successfully stored at " + +numSuccessfulStores + " locations.");
        }

        public void receiveException(Exception result) {
            System.out.println("Error storing ");
            result.printStackTrace();
            control.release();

        }
    });

    try {
        control.tryAcquire(1000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        log.error("Time out while trying to insert Property tree into DHT");
    }
}

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

@Test
@SuppressWarnings("unchecked")
public void buildManually_shouldSuspendPoller() throws Exception {
    final Semaphore eventSync = new Semaphore(0);
    when(workflowService.startFlow(eq("ci"), any(Map.class))).thenReturn(1L);
    doAnswer(new Answer<Void>() {
        @Override/*from  ww  w  .j  a  va2  s. c  o  m*/
        public Void answer(InvocationOnMock invocation) throws Throwable {
            eventSync.acquire();
            return null;
        }
    }).when(workflowService).waitForFlowToFinish(eq(1L), anyLong());
    when(scmMock.update()).thenReturn(null);

    Project project = new Project("test");
    project.setState(State.OK);
    projectManager.createProject(project);
    Thread.sleep(200);
    scheduler.scheduleProjectForBuild("test", new TestBuild());
    assertThat(scheduler.isProjectBuilding("test"), is(true));
    assertThat(scheduler.isProjectPolling("test"), is(false));
    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.impetus.ankush2.cassandra.deployer.CassandraDeployer.java

/**
 * method to deploy Cassandra packages on all nodes
 * //from   w ww. j  ava  2 s. c  om
 * @param conf
 *            {@link ClusterConfig}
 * @param nodeMap
 *            {@link Map}
 * 
 * @return <code>true</code>, if successful
 * 
 */
private boolean deployNodes(final ClusterConfig conf, Set<String> nodeMap) throws AnkushException {

    try {
        // Node Deployment process ...
        final Semaphore semaphore = new Semaphore(nodeMap.size());
        for (final String host : nodeMap) {
            semaphore.acquire();
            AppStoreWrapper.getExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    conf.getNodes().get(host).setStatus(createNode(host));
                    if (semaphore != null) {
                        semaphore.release();
                    }
                }
            });
        }
        semaphore.acquire(nodeMap.size());
    } catch (Exception e) {
        throw new AnkushException("Could not deploy " + getComponentName(), e);
    }
    return AnkushUtils.getStatus(conf.getNodes());
}

From source file:org.telepatch.ui.ChatActivity.java

@Override
public boolean onFragmentCreate() {
    final int chatId = arguments.getInt("chat_id", 0);
    final int userId = arguments.getInt("user_id", 0);
    final int encId = arguments.getInt("enc_id", 0);
    scrollToTopOnResume = arguments.getBoolean("scrollToTopOnResume", false);

    if (chatId != 0) {
        currentChat = MessagesController.getInstance().getChat(chatId);
        if (currentChat == null) {
            final Semaphore semaphore = new Semaphore(0);
            MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
                @Override/*www  .jav a 2  s. c om*/
                public void run() {
                    currentChat = MessagesStorage.getInstance().getChat(chatId);
                    semaphore.release();
                }
            });
            try {
                semaphore.acquire();
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
            if (currentChat != null) {
                MessagesController.getInstance().putChat(currentChat, true);
            } else {
                return false;
            }
        }
        if (chatId > 0) {
            dialog_id = -chatId;
        } else {
            isBroadcast = true;
            dialog_id = AndroidUtilities.makeBroadcastId(chatId);
        }
        Semaphore semaphore = null;
        if (isBroadcast) {
            semaphore = new Semaphore(0);
        }
        MessagesController.getInstance().loadChatInfo(currentChat.id, semaphore);
        if (isBroadcast) {
            try {
                semaphore.acquire();
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    } else if (userId != 0) {
        currentUser = MessagesController.getInstance().getUser(userId);
        if (currentUser == null) {
            final Semaphore semaphore = new Semaphore(0);
            MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
                @Override
                public void run() {
                    currentUser = MessagesStorage.getInstance().getUser(userId);
                    semaphore.release();
                }
            });
            try {
                semaphore.acquire();
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
            if (currentUser != null) {
                MessagesController.getInstance().putUser(currentUser, true);
            } else {
                return false;
            }
        }
        dialog_id = userId;
    } else if (encId != 0) {
        currentEncryptedChat = MessagesController.getInstance().getEncryptedChat(encId);
        if (currentEncryptedChat == null) {
            final Semaphore semaphore = new Semaphore(0);
            MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
                @Override
                public void run() {
                    currentEncryptedChat = MessagesStorage.getInstance().getEncryptedChat(encId);
                    semaphore.release();
                }
            });
            try {
                semaphore.acquire();
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
            if (currentEncryptedChat != null) {
                MessagesController.getInstance().putEncryptedChat(currentEncryptedChat, true);
            } else {
                return false;
            }
        }
        currentUser = MessagesController.getInstance().getUser(currentEncryptedChat.user_id);
        if (currentUser == null) {
            final Semaphore semaphore = new Semaphore(0);
            MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
                @Override
                public void run() {
                    currentUser = MessagesStorage.getInstance().getUser(currentEncryptedChat.user_id);
                    semaphore.release();
                }
            });
            try {
                semaphore.acquire();
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
            if (currentUser != null) {
                MessagesController.getInstance().putUser(currentUser, true);
            } else {
                return false;
            }
        }
        dialog_id = ((long) encId) << 32;
        maxMessageId = Integer.MIN_VALUE;
        minMessageId = Integer.MAX_VALUE;
        MediaController.getInstance().startMediaObserver();
    } else {
        return false;
    }

    //TODO qui elimino la notifica una volta entrato nella chat
    if (preferences.getBoolean("multiple_notify", true)) {
        nm.cancel((int) dialog_id);
    } else {
        nm.cancel(1);
    }

    chatActivityEnterView = new ChatActivityEnterView();
    chatActivityEnterView.setDialogId(dialog_id);
    chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() {
        @Override
        public void onMessageSend() {
            chatListView.post(new Runnable() {
                @Override
                public void run() {
                    chatListView.setSelectionFromTop(messages.size() - 1,
                            -100000 - chatListView.getPaddingTop());
                }
            });
        }

        @Override
        public void needSendTyping() {
            MessagesController.getInstance().sendTyping(dialog_id, classGuid);
        }
    });
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.didReceivedNewMessages);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesRead);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesDeleted);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByServer);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByAck);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageSendError);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.encryptedChatUpdated);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesReadedEncrypted);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.removeAllMessagesFromDialog);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidReset);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.screenshotTook);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.blockedUsersDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileNewChunkAvailable);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.didCreatedNewDeleteTask);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidStarted);

    super.onFragmentCreate();

    loading = true;

    MessagesController.getInstance().loadMessages(dialog_id, AndroidUtilities.isTablet() ? 30 : 20, 0, true, 0,
            classGuid, true, false, null);

    if (currentUser != null) {
        userBlocked = MessagesController.getInstance().blockedUsers.contains(currentUser.id);
    }

    if (AndroidUtilities.isTablet()) {
        NotificationCenter.getInstance().postNotificationName(NotificationCenter.openedChatChanged, dialog_id,
                false);
    }

    typingDotsDrawable = new TypingDotsDrawable();
    typingDotsDrawable.setIsChat(currentChat != null);

    if (currentEncryptedChat != null && AndroidUtilities
            .getMyLayerVersion(currentEncryptedChat.layer) != SendMessagesHelper.CURRENT_SECRET_CHAT_LAYER) {
        SendMessagesHelper.getInstance().sendNotifyLayerMessage(currentEncryptedChat, null);
    }

    return true;
}

From source file:com.parse.ParsePushTest.java

@Test
public void testSubscribeInBackgroundWithCallbackFail() throws Exception {
    ParsePushChannelsController controller = mock(ParsePushChannelsController.class);
    final ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error");
    when(controller.subscribeInBackground(anyString())).thenReturn(Task.<Void>forError(exception));
    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//from w ww  .  j  a va  2s . c om
        public void done(ParseException e) {
            exceptionCapture.set(e);
            done.release();
        }
    });
    assertSame(exception, exceptionCapture.get());
    assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
    verify(controller, times(1)).subscribeInBackground("test");
}

From source file:com.baifendian.swordfish.execserver.runner.flow.FlowRunner.java

/**
 * ? DAG: 1. ? start  2. , ??? 3. , ?, ,  END, ,  4 4.
 * , ?, ?, ?,  5 5. ?, ??, ??,  2 6. ?,  SUCCESS <p>
 * END: ??, ; ??/*from  w  ww . j a va  2s.  c om*/
 */

private FlowStatus runFlow(Graph<String, FlowNode, FlowNodeRelation> dagGraph) {
    // ??, ??
    Semaphore semaphore = new Semaphore(0);

    //  dagGraph ??, ??
    try {
        for (String nodeName : dagGraph.topologicalSort()) {
            ExecutionNode executionNode = flowDao.queryExecutionNode(executionFlow.getId(), nodeName);

            // ?
            if (executionNode != null && executionNode.getStatus().typeIsFinished()) {
                dagGraph.removeVertex(nodeName);
            }
        }
    } catch (Exception e) {
        logger.error("Get topological of graph failed.", e);
        return FlowStatus.FAILED;
    }

    // 
    Collection<String> startVertex = dagGraph.getStartVertex();

    // ??
    for (String nodeName : startVertex) {
        if (!executionNodeMap.containsKey(nodeName)) {
            // ?
            ExecutionNode executionNode = insertExecutionNode(executionFlow, nodeName);

            // 
            executionNodeMap.put(nodeName, executionNode);

            // ??
            submitNodeRunner(dagGraph.getVertex(nodeName), executionNode, semaphore);
        }
    }

    // ?
    FlowStatus status = FlowStatus.SUCCESS;

    // ?, 
    while (!activeNodeRunners.isEmpty()) {
        boolean acquire = false;

        try {
            // , , 
            acquire = semaphore.tryAcquire(calcNodeTimeout(), TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        } catch (ExecTimeoutException e) {
            logger.error(e.getMessage(), e);
        }

        // ?, ?
        if (!acquire) {
            clean(true);
            return FlowStatus.FAILED;
        }

        // ?, ?
        boolean done = false;

        while (!done) {
            // ?
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                logger.error(e.getMessage(), e);
            }

            // ??, ??
            for (Map.Entry<NodeRunner, Future<Boolean>> entry : activeNodeRunners.entrySet()) {
                NodeRunner nodeRunner = entry.getKey();
                Future<Boolean> future = entry.getValue();

                // ?
                if (future.isDone()) {
                    // ?
                    done = true;

                    // , 
                    activeNodeRunners.remove(nodeRunner);

                    Boolean value = false;

                    Date now = new Date();

                    try {
                        value = future.get();
                    } catch (CancellationException e) {
                        logger.error("task has been cancel");

                        // ?
                        clean(true);
                        return FlowStatus.KILL;
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(), e);
                    } catch (ExecutionException e) {
                        logger.error(e.getMessage(), e);
                    }

                    // 
                    if (!value) {
                        // ?, ???
                        ExecutionNode executionNode = executionNodeMap.get(nodeRunner.getNodename());

                        // ,  2, ?? 2 
                        if (executionNode.getAttempt() < maxTryTimes) {
                            executionNode.incAttempt();

                            // ?
                            flowDao.updateExecutionNode(executionNode);

                            // ???
                            submitNodeRunner(dagGraph.getVertex(nodeRunner.getNodename()), executionNode,
                                    semaphore);
                        } else {
                            // ??
                            status = FlowStatus.FAILED;

                            executionNode.setEndTime(now);
                            executionNode.setStatus(status);

                            // ?
                            flowDao.updateExecutionNode(executionNode);

                            if (failurePolicyType == FailurePolicyType.END) {
                                clean(true);
                                return status;
                            }
                        }
                    } else { // ?
                        // ?
                        ExecutionNode executionNode = executionNodeMap.get(nodeRunner.getNodename());

                        executionNode.setEndTime(now);
                        executionNode.setStatus(FlowStatus.SUCCESS);

                        flowDao.updateExecutionNode(executionNode);

                        // ?, ?, ???
                        for (String nodeName : dagGraph.getPostNode(nodeRunner.getNodename())) {
                            if (!executionNodeMap.containsKey(nodeName)
                                    && isPreNodesAllSuccess(dagGraph.getPreNode(nodeName))) {
                                // ?
                                ExecutionNode newExecutionNode = insertExecutionNode(executionFlow, nodeName);

                                // 
                                executionNodeMap.put(nodeName, newExecutionNode);

                                // ??
                                submitNodeRunner(dagGraph.getVertex(nodeName), newExecutionNode, semaphore);
                            }
                        }
                    }

                    break;
                }
            }
        }
    }

    return status;
}