Tabnine Logo
Semaphore
Code IndexAdd Tabnine to your IDE (free)

How to use
Semaphore
in
java.util.concurrent

Best Java code snippets using java.util.concurrent.Semaphore (Showing top 20 results out of 10,764)

origin: netty/netty

@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
  if (unit == null) {
    throw new NullPointerException("unit");
  }
  if (inEventLoop()) {
    throw new IllegalStateException("cannot await termination of the current thread");
  }
  if (threadLock.tryAcquire(timeout, unit)) {
    threadLock.release();
  }
  return isTerminated();
}
origin: google/guava

 @Override
 public Semaphore get() {
  return new Semaphore(permits, false);
 }
});
origin: redisson/redisson

public void addCall(final FSTRunnable toRun) throws InterruptedException {
  gateway.acquire();
  if (jobs[curIdx] == null) {
    jobs[curIdx] = toRun;
  } else {
    jobs[curIdx].sem.acquire();
    jobs[curIdx].sem.release();
    jobs[curIdx] = toRun;
  }
  toRun.sem = sems[curIdx];
  toRun.sem.acquire();
  OrderedRunnable ord = orderedRunnableCache[curIdx];
  ord.toRun = toRun;
  curIdx = (curIdx + 1) % threads;
  orderedPool.execute(ord);
  pool.execute(toRun);
}
origin: redisson/redisson

public void waitForFinish() throws InterruptedException {
  final Semaphore sem = new Semaphore(0);
  orderedPool.execute(new Runnable() {
    @Override
    public void run() {
      sem.release();
    }
  });
  sem.acquire();
}
origin: pentaho/pentaho-kettle

@Override public synchronized void resume() {
 if ( paused.getAndSet( false ) ) {
  assert acceptingRowsSemaphore.availablePermits() == 0;
  acceptingRowsSemaphore.release();
 }
}
origin: ReactiveX/RxJava

@Override
public void onNext(Notification<T> args) {
  boolean wasNotAvailable = value.getAndSet(args) == null;
  if (wasNotAvailable) {
    notify.release();
  }
}
origin: Alluxio/alluxio

@Override
public void lockInterruptibly() throws InterruptedException {
 mAvailable.acquire(mPermits);
}
origin: Alluxio/alluxio

@Override
public boolean tryLock() {
 return mAvailable.tryAcquire(mPermits);
}
origin: neo4j/neo4j

@AfterEach
private void refillSemaphore()
{
  // This ensures that no threads end up stuck
  semaphore.drainPermits();
  semaphore.release( Integer.MAX_VALUE );
}
origin: pentaho/pentaho-kettle

@Test
@SuppressWarnings ( "unchecked" )
public void errorLoggedIfInterruptedInPause() throws InterruptedException {
 streamSource.acceptingRowsSemaphore = semaphore;
 when( semaphore.availablePermits() ).thenReturn( 1 );
 streamSource.logChannel = logChannel;
 doThrow( new InterruptedException( "interrupt" ) )
  .when( semaphore ).acquire();
 streamSource.pause();
 verify( logChannel ).logError( any() );
}
origin: resilience4j/resilience4j

/**
 * {@inheritDoc}
 */
@Override
public int getAvailablePermissions() {
  return semaphore.availablePermits();
}
origin: ReactiveX/RxJava

@Override
public void onNext(Notification<T> args) {
  boolean wasNotAvailable = value.getAndSet(args) == null;
  if (wasNotAvailable) {
    notify.release();
  }
}
origin: robolectric/robolectric

public void lock() {
 try {
  mLock.acquire();
 } catch (InterruptedException e) {
  throw new RuntimeException(e);
 }
}
origin: apache/storm

public void feed(Object tuples) {
  Semaphore sem = new Semaphore(0);
  ((List) RegisteredGlobalState.getState(_semaphoreId)).add(sem);
  ((List) RegisteredGlobalState.getState(_id)).add(tuples);
  try {
    sem.acquire();
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
}
origin: Alluxio/alluxio

@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
 return mAvailable.tryAcquire(mPermits, time, unit);
}
origin: resilience4j/resilience4j

void refreshLimit() {
  int permissionsToRelease = this.rateLimiterConfig.get().getLimitForPeriod() - semaphore.availablePermits();
  semaphore.release(permissionsToRelease);
}
origin: resilience4j/resilience4j

  @Override
  public int getAvailableConcurrentCalls() {
    return semaphore.availablePermits();
  }
}
origin: redisson/redisson

@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
  if (unit == null) {
    throw new NullPointerException("unit");
  }
  if (inEventLoop()) {
    throw new IllegalStateException("cannot await termination of the current thread");
  }
  if (threadLock.tryAcquire(timeout, unit)) {
    threadLock.release();
  }
  return isTerminated();
}
origin: redisson/redisson

  @Override
  public void run() {
    sem.release();
  }
});
origin: prestodb/presto

 @Override
 public Semaphore get() {
  return new Semaphore(permits, false);
 }
});
java.util.concurrentSemaphore

Javadoc

A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each #acquire blocks if necessary until a permit is available, and then takes it. Each #release adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.

Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource. For example, here is a class that uses a semaphore to control access to a pool of items:

  
class Pool public void putItem(Object x)  
if (markAsUnused(x)) 
available.release(); 
} 
// Not a particularly efficient data structure; just for demo 
protected Object[] items = ... whatever kinds of items being managed 
protected boolean[] used = new boolean[MAX_AVAILABLE]; 
protected synchronized Object getNextAvailableItem()  
for (int i = 0; i < MAX_AVAILABLE; ++i)  
if (!used[i])  
used[i] = true; 
return items[i]; 
} 
} 
return null; // not reached 
} 
protected synchronized boolean markAsUnused(Object item)  
for (int i = 0; i < MAX_AVAILABLE; ++i)  
if (item == items[i])  
if (used[i])  
used[i] = false; 
return true; 
} else 
return false; 
} 
} 
return false; 
} 
}}

Before obtaining an item each thread must acquire a permit from the semaphore, guaranteeing that an item is available for use. When the thread has finished with the item it is returned back to the pool and a permit is returned to the semaphore, allowing another thread to acquire that item. Note that no synchronization lock is held when #acquire is called as that would prevent an item from being returned to the pool. The semaphore encapsulates the synchronization needed to restrict access to the pool, separately from any synchronization needed to maintain the consistency of the pool itself.

A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available. When used in this way, the binary semaphore has the property (unlike many java.util.concurrent.locks.Lockimplementations), that the "lock" can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.

The constructor for this class optionally accepts a fairness parameter. When set false, this class makes no guarantees about the order in which threads acquire permits. In particular, barging is permitted, that is, a thread invoking #acquire can be allocated a permit ahead of a thread that has been waiting - logically the new thread places itself at the head of the queue of waiting threads. When fairness is set true, the semaphore guarantees that threads invoking any of the #acquire() methods are selected to obtain permits in the order in which their invocation of those methods was processed (first-in-first-out; FIFO). Note that FIFO ordering necessarily applies to specific internal points of execution within these methods. So, it is possible for one thread to invoke acquire before another, but reach the ordering point after the other, and similarly upon return from the method. Also note that the untimed #tryAcquire() methods do not honor the fairness setting, but will take any permits that are available.

Generally, semaphores used to control resource access should be initialized as fair, to ensure that no thread is starved out from accessing a resource. When using semaphores for other kinds of synchronization control, the throughput advantages of non-fair ordering often outweigh fairness considerations.

This class also provides convenience methods to #acquire(int) and #release(int) multiple permits at a time. Beware of the increased risk of indefinite postponement when these methods are used without fairness set true.

Memory consistency effects: Actions in a thread prior to calling a "release" method such as release()happen-before actions following a successful "acquire" method such as acquire()in another thread.

Most used methods

  • release
    Releases the given number of permits, returning them to the semaphore.Releases the given number of p
  • <init>
    Creates a Semaphore with the given number of permits and the given fairness setting.
  • acquire
    Acquires the given number of permits from this semaphore, blocking until all are available, or the t
  • tryAcquire
    Acquires a permit from this semaphore, if one becomes available within the given waiting time and th
  • availablePermits
    Returns the current number of permits available in this semaphore.This method is typically used for
  • acquireUninterruptibly
    Acquires the given number of permits from this semaphore, blocking until all are available.Acquires
  • drainPermits
    Acquires and returns all permits that are immediately available.
  • getQueueLength
    Returns an estimate of the number of threads waiting to acquire. The value is only an estimate becau
  • hasQueuedThreads
    Queries whether any threads are waiting to acquire. Note that because cancellations may occur at any
  • reducePermits
    Shrinks the number of available permits by the indicated reduction. This method can be useful in sub
  • toString
    Returns a string identifying this semaphore, as well as its state. The state, in brackets, includes
  • isFair
    Returns true if this semaphore has fairness set true.
  • toString,
  • isFair,
  • getQueuedThreads

Popular in Java

  • Reactive rest calls using spring rest template
  • addToBackStack (FragmentTransaction)
  • getApplicationContext (Context)
  • getResourceAsStream (ClassLoader)
  • Window (java.awt)
    A Window object is a top-level window with no borders and no menubar. The default layout for a windo
  • Comparator (java.util)
    A Comparator is used to compare two objects to determine their ordering with respect to each other.
  • HashMap (java.util)
    HashMap is an implementation of Map. All optional operations are supported.All elements are permitte
  • LinkedList (java.util)
    Doubly-linked list implementation of the List and Dequeinterfaces. Implements all optional list oper
  • Vector (java.util)
    Vector is an implementation of List, backed by an array and synchronized. All optional operations in
  • AtomicInteger (java.util.concurrent.atomic)
    An int value that may be updated atomically. See the java.util.concurrent.atomic package specificati
  • Top Sublime Text plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now