Example usage for java.util.concurrent Semaphore tryAcquire

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

Introduction

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

Prototype

public boolean tryAcquire(int permits) 

Source Link

Document

Acquires the given number of permits from this semaphore, only if all are available at the time of invocation.

Usage

From source file:net.tomp2p.simgrid.SimGridTomP2P.java

private static void createPeers(int nr) {
    for (int i = 0; i < nr; i++) {
        Number160 peerID = Number160.createHash("" + i);
        mailboxMapping.put(peerID, "" + i);
        Peer peer = new Peer(peerID);

        peer.getP2PConfiguration().setDisableBind(true);
        peer.getP2PConfiguration().setStartMaintenance(false);

        try {/*from   w  ww  . j a v  a  2s.c  om*/
            peer.listen();
            peer.getConnectionBean().getConnectionReservation().setReservation(new Reservation() {
                private volatile boolean shutdown = false;

                @Override
                public void shutdown() {
                    shutdown = true;
                }

                @Override
                public boolean acquire(Semaphore semaphore, int permits) {
                    boolean acquired = false;
                    while (!acquired && !shutdown) {
                        try {
                            acquired = semaphore.tryAcquire(permits);
                            if (!acquired) {
                                synchronized (semaphore) {
                                    Process.sleep(0);
                                }
                            }
                        } catch (HostFailureException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    return acquired;
                }

                @Override
                public void runDeadLockProof(Scheduler scheduler, FutureRunnable futureRunnable) {
                    futureRunnable.run();
                }

                @Override
                public void prepareDeadLockCheck() {
                    //nothing to do
                }

                @Override
                public void removeDeadLockCheck(long creatorThread) {
                    //nothing to do
                }
            });
            emulateSender(peer);
            peers.put(peerID, peer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Msg.info("created peer with peerID " + peerID);
    }
    Msg.info("peers created");
}