Example usage for java.util.concurrent Semaphore release

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

Introduction

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

Prototype

public void release() 

Source Link

Document

Releases a permit, returning it to the semaphore.

Usage

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

final void updateMappedDocValues(final Map<String, Object> document) throws IOException, InterruptedException {
    if (document == null || document.isEmpty())
        return;/* w w w  .j a v  a  2  s .  c  om*/
    final Semaphore sem = schema.acquireWriteSemaphore();
    try {
        RecordsPoster.UpdateMapDocValues poster = getDocValuesPoster();
        poster.accept(document);
        nrtCommit();
    } finally {
        if (sem != null)
            sem.release();
    }
}

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

final void updateMappedDocsValues(final Collection<Map<String, Object>> documents)
        throws IOException, ServerException, InterruptedException {
    if (documents == null || documents.isEmpty())
        return;/*from   ww w  .j a  v  a  2 s .c  o  m*/
    final Semaphore sem = schema.acquireWriteSemaphore();
    try {
        RecordsPoster.UpdateMapDocValues poster = getDocValuesPoster();
        documents.forEach(poster);
        nrtCommit();
    } finally {
        if (sem != null)
            sem.release();
    }
}

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

final <T> void updateDocValues(final Map<String, Field> fields, final T document)
        throws InterruptedException, IOException {
    if (document == null)
        return;/*  w  w w . j  ava  2s.  c  o m*/
    final Semaphore sem = schema.acquireWriteSemaphore();
    try {
        RecordsPoster.UpdateObjectDocValues poster = getDocValuesPoster(fields);
        poster.accept(document);
        nrtCommit();
    } finally {
        if (sem != null)
            sem.release();
    }
}

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

final <T> void updateDocsValues(final Map<String, Field> fields, final Collection<T> documents)
        throws IOException, InterruptedException {
    if (documents == null || documents.isEmpty())
        return;/*from ww  w. j  av  a  2 s. com*/
    final Semaphore sem = schema.acquireWriteSemaphore();
    try {
        RecordsPoster.UpdateObjectDocValues poster = getDocValuesPoster(fields);
        documents.forEach(poster);
        nrtCommit();
    } finally {
        if (sem != null)
            sem.release();
    }
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessSemaphoreCluster.java

@Test
public void testKilledServerWithEnsembleProvider() throws Exception {
    final int CLIENT_QTY = 10;
    final Timing timing = new Timing();
    final String PATH = "/foo/bar/lock";

    ExecutorService executorService = Executors.newFixedThreadPool(CLIENT_QTY);
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executorService);
    TestingCluster cluster = new TestingCluster(3);
    try {/*ww  w . j  a va 2s  .co  m*/
        cluster.start();

        final AtomicReference<String> connectionString = new AtomicReference<String>(
                cluster.getConnectString());
        final EnsembleProvider provider = new EnsembleProvider() {
            @Override
            public void start() throws Exception {
            }

            @Override
            public String getConnectionString() {
                return connectionString.get();
            }

            @Override
            public void close() throws IOException {
            }
        };

        final Semaphore acquiredSemaphore = new Semaphore(0);
        final AtomicInteger acquireCount = new AtomicInteger(0);
        final CountDownLatch suspendedLatch = new CountDownLatch(CLIENT_QTY);
        for (int i = 0; i < CLIENT_QTY; ++i) {
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    CuratorFramework client = CuratorFrameworkFactory.builder().ensembleProvider(provider)
                            .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection())
                            .retryPolicy(new ExponentialBackoffRetry(100, 3)).build();
                    try {
                        final Semaphore suspendedSemaphore = new Semaphore(0);
                        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
                            @Override
                            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                                if ((newState == ConnectionState.SUSPENDED)
                                        || (newState == ConnectionState.LOST)) {
                                    suspendedLatch.countDown();
                                    suspendedSemaphore.release();
                                }
                            }
                        });

                        client.start();

                        InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, PATH, 1);

                        while (!Thread.currentThread().isInterrupted()) {
                            Lease lease = null;
                            try {
                                lease = semaphore.acquire();
                                acquiredSemaphore.release();
                                acquireCount.incrementAndGet();
                                suspendedSemaphore.acquire();
                            } catch (Exception e) {
                                // just retry
                            } finally {
                                if (lease != null) {
                                    acquireCount.decrementAndGet();
                                    IOUtils.closeQuietly(lease);
                                }
                            }
                        }
                    } finally {
                        IOUtils.closeQuietly(client);
                    }
                    return null;
                }
            });
        }

        Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore));
        Assert.assertEquals(1, acquireCount.get());

        cluster.close();
        timing.awaitLatch(suspendedLatch);
        timing.forWaiting().sleepABit();
        Assert.assertEquals(0, acquireCount.get());

        cluster = new TestingCluster(3);
        cluster.start();

        connectionString.set(cluster.getConnectString());
        timing.forWaiting().sleepABit();

        Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore));
        timing.forWaiting().sleepABit();
        Assert.assertEquals(1, acquireCount.get());
    } finally {
        executorService.shutdown();
        executorService.awaitTermination(10, TimeUnit.SECONDS);
        executorService.shutdownNow();
        IOUtils.closeQuietly(cluster);
    }
}

From source file:com.yahala.ui.GroupCreateFinalActivity.java

@SuppressWarnings("unchecked")
@Override/*from w  w  w . jav a2s  .  c o m*/
public boolean onFragmentCreate() {
    NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces);
    NotificationCenter.getInstance().addObserver(this, MessagesController.chatDidCreated);
    NotificationCenter.getInstance().addObserver(this, MessagesController.chatDidFailCreate);
    avatarUpdater.parentFragment = this;
    avatarUpdater.delegate = this;
    selectedContacts = getArguments().getStringArrayList("result");
    final ArrayList<String> usersToLoad = new ArrayList<String>();
    for (String jid : selectedContacts) {
        TLRPC.User user = ContactsController.getInstance().friendsDict.get(jid);
        if (user == null) {
            usersToLoad.add(jid);
        }
    }
    if (!usersToLoad.isEmpty()) {
        final Semaphore semaphore = new Semaphore(0);
        final ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
        final boolean[] error = new boolean[1];
        MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
            @Override
            public void run() {
                users.addAll(MessagesStorage.getInstance().getUsers(usersToLoad, error));
                semaphore.release();
            }
        });
        try {
            semaphore.acquire();
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
        //if (error[0]) {
        //    return false;
        // }
        if (!users.isEmpty()) {
            for (TLRPC.User user : users) {
                ContactsController.getInstance().friendsDict.putIfAbsent(user.jid, user);
            }
        } else {
            return false;
        }
    }
    super.onFragmentCreate();
    return true;
}

From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelector.java

@Test
public void testKillSession() throws Exception {
    final Timing timing = new Timing();

    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    client.start();//from w w w .  jav  a  2s .  c  om
    try {
        final Semaphore semaphore = new Semaphore(0);
        final CountDownLatch interruptedLatch = new CountDownLatch(1);
        final AtomicInteger leaderCount = new AtomicInteger(0);
        LeaderSelectorListener listener = new LeaderSelectorListener() {
            private volatile Thread ourThread;

            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                leaderCount.incrementAndGet();
                try {
                    ourThread = Thread.currentThread();
                    semaphore.release();
                    try {
                        Thread.sleep(1000000);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        interruptedLatch.countDown();
                    }
                } finally {
                    leaderCount.decrementAndGet();
                }
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if ((newState == ConnectionState.LOST) && (ourThread != null)) {
                    ourThread.interrupt();
                }
            }
        };
        LeaderSelector leaderSelector1 = new LeaderSelector(client, PATH_NAME, listener);
        LeaderSelector leaderSelector2 = new LeaderSelector(client, PATH_NAME, listener);

        leaderSelector1.start();
        leaderSelector2.start();

        Assert.assertTrue(timing.acquireSemaphore(semaphore, 1));

        KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString());

        Assert.assertTrue(timing.awaitLatch(interruptedLatch));
        timing.sleepABit();

        leaderSelector1.requeue();
        leaderSelector2.requeue();

        Assert.assertTrue(timing.acquireSemaphore(semaphore, 1));
        Assert.assertEquals(leaderCount.get(), 1);

        leaderSelector1.close();
        leaderSelector2.close();
    } finally {
        client.close();
    }
}

From source file:edu.chalmers.dat076.moviefinder.service.MovieFileDatabaseHandlerImpl.java

@Override
@Transactional/* w w w.j a  v a 2s  . co  m*/
public void removeFile(Path path) {
    try {
        movieSemaphore.acquire();
        List<Movie> movies = movieRepository.findAllByFilePathStartingWith(path.toString());
        for (Movie m : movies) {
            movieRepository.delete(m);
        }
    } catch (InterruptedException ex) {
    } finally {
        movieSemaphore.release();
    }

    List<Episode> episodes = episodeRepository.findAllByFilePathStartingWith(path.toString());
    for (Episode m : episodes) {
        Semaphore sLock = serieLock.get(m.getSeries().getTitle());
        if (sLock == null) {
            sLock = new Semaphore(1, true);
            serieLock.put(m.getSeries().getTitle(), sLock);
        }

        try {
            sLock.acquire();
            Series s = m.getSeries();
            s.getEpisodes().remove(m);
            episodeRepository.delete(m);
            if (s.getEpisodes().isEmpty()) {
                seriesRepository.delete(s);
            } else {
                seriesRepository.save(s);
            }
        } catch (InterruptedException ex) {
        } finally {
            sLock.release();
        }

    }

}

From source file:org.paxle.core.threading.AWorkerTest.java

public void testWorkerTriggeredAndReturnToPool() throws InterruptedException {
    final ICommand command = mock(ICommand.class);
    final DummyWorker worker = new DummyWorker();
    final Semaphore waitforReturnToPool = new Semaphore(0);

    checking(new Expectations() {
        {/*from w ww .j  av  a  2 s . co m*/
            // allow enqueuing and dequeueing of exactly one command
            one(inQueue).dequeue();
            will(returnValue(command));
            one(outQueue).enqueue(with(same(command)));

            // pool is not closed
            one(pool).closed();
            will(returnValue(false));

            // worker must return itself into pool
            one(pool).returnWorker(with(same(worker)));
            will(new Action() {
                public void describeTo(Description arg0) {
                }

                public Object invoke(Invocation invocation) throws Throwable {
                    waitforReturnToPool.release();
                    return null;
                }
            });
        }
    });

    // init worker
    worker.setInQueue(this.inQueue);
    worker.setOutQueue(this.outQueue);
    worker.setPool(this.pool);

    // trigger worker to dequeue and process new command
    worker.trigger();

    // wait until worker has returned itself into pool
    assertTrue(waitforReturnToPool.tryAcquire(5, TimeUnit.SECONDS));

    // terminate worker
    worker.terminate();
    assertTrue(worker.commandProcessed);
}

From source file:org.telegram.ui.ChannelEditActivity.java

@SuppressWarnings("unchecked")
@Override//from w w w  . j a  v  a2  s.  co m
public boolean onFragmentCreate() {
    currentChat = MessagesController.getInstance().getChat(chatId);
    if (currentChat == null) {
        final Semaphore semaphore = new Semaphore(0);
        MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
            @Override
            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 (info == null) {
            MessagesStorage.getInstance().loadChatInfo(chatId, semaphore, false, false);
            try {
                semaphore.acquire();
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
            if (info == null) {
                return false;
            }
        }
    }
    avatarUpdater.parentFragment = this;
    avatarUpdater.delegate = this;
    signMessages = currentChat.signatures;
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
    return super.onFragmentCreate();
}