Java Code Examples for java.util.concurrent.Semaphore

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project android-rackspacecloud, under directory /extensions/httpnio/src/main/java/org/jclouds/http/pool/.

Source file: HttpCommandConnectionHandle.java

  22 
vote

public HttpCommandConnectionHandle(Semaphore maxConnections,BlockingQueue<C> available,URI endPoint,HttpCommandRendezvous<?> command,C conn) throws InterruptedException {
  this.available=available;
  this.maxConnections=maxConnections;
  this.completed=new Semaphore(1);
  this.endPoint=endPoint;
  this.command=command;
  this.conn=conn;
  completed.acquire();
}
 

Example 2

From project Arecibo, under directory /agent/src/main/java/com/ning/arecibo/agent/.

Source file: AgentDataCollectorManager.java

  22 
vote

public boolean tryAcquirePerHostSemaphore(String host){
  Semaphore sem=perHostSemaphoreMap.get(host);
  try {
    return sem.tryAcquire(agentConfig.getPerHostSemaphoreMaxWait().getPeriod(),agentConfig.getPerHostSemaphoreMaxWait().getUnit());
  }
 catch (  InterruptedException ieEx) {
    return false;
  }
}
 

Example 3

From project CommitCoin, under directory /src/com/google/bitcoin/utils/.

Source file: NamedSemaphores.java

  22 
vote

private Semaphore getSemaphore(String name){
synchronized (lockMap) {
    Semaphore s=lockMap.get(name);
    if (s == null) {
      s=new Semaphore(1);
      lockMap.put(name,s);
    }
    return s;
  }
}
 

Example 4

From project openengsb-framework, under directory /components/services/src/main/java/org/openengsb/core/services/internal/deployer/connector/.

Source file: ConnectorDeployerService.java

  22 
vote

@Override public void update(File artifact) throws Exception {
  LOGGER.debug("ConnectorDeployer.update(\"{}\")",artifact.getAbsolutePath());
  Semaphore semaphore=updateSemaphores.get(artifact);
  semaphore.acquire();
  try {
    doUpdate(artifact);
  }
  finally {
    semaphore.release();
  }
}
 

Example 5

From project riak-java-client, under directory /src/main/java/com/basho/riak/client/raw/pbc/.

Source file: PBClusterClient.java

  22 
vote

@Override protected RawClient[] fromConfig(ClusterConfig<PBClientConfig> clusterConfig) throws IOException {
  final List<PBClientAdapter> clients=new ArrayList<PBClientAdapter>();
  int totalMaxConnections=clusterConfig.getTotalMaximumConnections();
  Semaphore clusterSemaphore=null;
  if (totalMaxConnections > RiakConnectionPool.LIMITLESS) {
    clusterSemaphore=RiakConnectionPool.getSemaphore(totalMaxConnections);
  }
  for (  PBClientConfig node : clusterConfig.getClients()) {
    final RiakConnectionPool hostPool=makePool(clusterSemaphore,node);
    hostPool.start();
    clients.add(new PBClientAdapter(new RiakClient(hostPool)));
  }
  return clients.toArray(new RawClient[clients.size()]);
}
 

Example 6

From project server-main, under directory /src/main/java/org/powertac/server/.

Source file: SimulationClockControl.java

  22 
vote

public void waitUntilStop(){
  Status state=getState();
  if (state != Status.STOPPED) {
    Semaphore sem=new Semaphore(0);
    waitUntilStopSemaphores.add(sem);
    try {
      sem.acquire();
    }
 catch (    InterruptedException e) {
      log.info("Who dares wake me up??",e);
    }
  }
}
 

Example 7

From project weel, under directory /src/main/java/com/github/rjeschke/weel/jclass/.

Source file: WeelSemaphore.java

  22 
vote

/** 
 * Acquire.
 * @param thiz This.
 * @param permits Number of permits.
 * @return false if the operation was interrupted.
 * @see java.util.concurrent.Semaphore#acquire(int)
 */
@WeelMethod public final static boolean acquire(final ValueMap thiz,final int permits){
  final Semaphore sem=WeelOop.getInstance(thiz,Semaphore.class);
  try {
    sem.acquire(permits);
    return true;
  }
 catch (  InterruptedException e) {
    return false;
  }
}
 

Example 8

From project zk-service-registry-server, under directory /lib/zk-service-registry-server/zookeeper-3.3.3/src/java/main/org/apache/zookeeper/server/quorum/.

Source file: AuthFastLeaderElection.java

  22 
vote

boolean saveChallenge(long tag,long challenge){
  Semaphore s=challengeMutex.get(tag);
  if (s != null) {
synchronized (challengeMap) {
      challengeMap.put(tag,challenge);
      challengeMutex.remove(tag);
    }
    s.release();
  }
 else {
    LOG.error("No challenge mutex object");
  }
  return true;
}
 

Example 9

From project zookeeper, under directory /src/java/main/org/apache/zookeeper/server/quorum/.

Source file: AuthFastLeaderElection.java

  22 
vote

boolean saveChallenge(long tag,long challenge){
  Semaphore s=challengeMutex.get(tag);
  if (s != null) {
synchronized (Messenger.this) {
      challengeMap.put(tag,challenge);
      challengeMutex.remove(tag);
    }
    s.release();
  }
 else {
    LOG.error("No challenge mutex object");
  }
  return true;
}
 

Example 10

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/.

Source file: Utils.java

  21 
vote

/** 
 * Replace all the chosen material in the cuboid region.
 * @param mat
 * @param block
 * @param radius
 * @return
 */
private static Stack<BlockRemanence> replaceInCuboid(final String playername,final List<Material> mat,final Block block,final int radius){
  final Stack<BlockRemanence> blocks=new SynchronizedStack<BlockRemanence>();
  final Stack<BlockRemanence> blocksCache=new SynchronizedStack<BlockRemanence>();
  final int limitX=block.getX() + radius;
  final int limitY=block.getY() + radius;
  final int limitZ=block.getZ() + radius;
  BlockRemanence br=null;
  final Semaphore sema=new Semaphore(0,true);
  final List<SimplifiedLocation> okBlocks=new ArrayList<SimplifiedLocation>(50);
  ACPluginManager.scheduleSyncTask(new CheckingBlockTask(sema,okBlocks,block,radius,limitY,limitX,limitZ,mat));
  try {
    sema.acquire();
  }
 catch (  final InterruptedException e) {
    DebugLog.INSTANCE.log(Level.SEVERE,"Problem with acquiring the semaphore",e);
  }
  for (  final SimplifiedLocation loc : okBlocks) {
    br=IBlockRemanenceFactory.FACTORY.createBlockRemanence(loc);
    blocks.push(br);
    blocksCache.push(br);
    if (blocksCache.size() == MAX_BLOCKS) {
      ACPluginManager.getScheduler().scheduleSyncDelayedTask(ACHelper.getInstance().getCoreInstance(),new ReplaceBlockTask(blocksCache),1);
    }
  }
  ACPluginManager.getScheduler().scheduleSyncDelayedTask(ACHelper.getInstance().getCoreInstance(),new ReplaceBlockTask(blocksCache),1);
  return blocks;
}
 

Example 11

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/test/java/org/apache/aries/blueprint/container/.

Source file: BPQuiesceTest.java

  21 
vote

@Test public void canQuiesceNoBPBundle() throws Exception {
  BundleContext ctx=Skeleton.newMock(BundleContext.class);
  Bundle bpBundle=Skeleton.newMock(Bundle.class);
  Bundle testBundle=Skeleton.newMock(Bundle.class);
  Skeleton.getSkeleton(ctx).setReturnValue(new MethodCall(BundleContext.class,"getBundle"),bpBundle);
  BlueprintQuiesceParticipant bqp=new BlueprintQuiesceParticipant(ctx,new BlueprintExtender(){
    @Override protected BlueprintContainerImpl getBlueprintContainerImpl(    Bundle bundle){
      return null;
    }
  }
);
  final Semaphore result=new Semaphore(0);
  QuiesceCallback qc=new QuiesceCallback(){
    public void bundleQuiesced(    Bundle... bundlesQuiesced){
      result.release();
    }
  }
;
  bqp.quiesce(qc,Arrays.asList(testBundle));
  assertTrue(result.tryAcquire(2,TimeUnit.SECONDS));
}
 

Example 12

From project CommunityCase, under directory /src/org/community/intellij/plugins/communitycase/checkout/branches/.

Source file: CheckoutProcess.java

  21 
vote

private void waitForChanges() throws VcsException {
  final Semaphore s=new Semaphore(0);
  waitForChangesRefresh("Preparing for the checkout: ",new Runnable(){
    @Override public void run(){
      s.release();
    }
  }
);
  try {
    s.acquire();
  }
 catch (  InterruptedException e) {
    throw new VcsException("Waiting for changes was interrupted: ",e);
  }
}
 

Example 13

From project curator, under directory /curator-framework/src/test/java/com/netflix/curator/framework/imps/.

Source file: TestFailedDeleteManager.java

  21 
vote

@Test public void testLostSession() throws Exception {
  Timing timing=new Timing();
  CuratorFramework client=CuratorFrameworkFactory.newClient(server.getConnectString(),timing.session(),timing.connection(),new ExponentialBackoffRetry(100,3));
  try {
    client.start();
    client.create().forPath("/test-me");
    final CountDownLatch latch=new CountDownLatch(1);
    final Semaphore semaphore=new Semaphore(0);
    ConnectionStateListener listener=new ConnectionStateListener(){
      @Override public void stateChanged(      CuratorFramework client,      ConnectionState newState){
        if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) {
          semaphore.release();
        }
 else         if (newState == ConnectionState.RECONNECTED) {
          latch.countDown();
        }
      }
    }
;
    client.getConnectionStateListenable().addListener(listener);
    server.stop();
    Assert.assertTrue(timing.acquireSemaphore(semaphore));
    try {
      client.delete().guaranteed().forPath("/test-me");
      Assert.fail();
    }
 catch (    KeeperException.ConnectionLossException e) {
    }
    Assert.assertTrue(timing.acquireSemaphore(semaphore));
    timing.sleepABit();
    server=new TestingServer(server.getPort(),server.getTempDirectory());
    Assert.assertTrue(timing.awaitLatch(latch));
    timing.sleepABit();
    Assert.assertNull(client.checkExists().forPath("/test-me"));
  }
  finally {
    Closeables.closeQuietly(client);
  }
}
 

Example 14

From project cxf-dosgi, under directory /dsw/cxf-topology-manager/src/test/java/org/apache/cxf/dosgi/topologymanager/.

Source file: TopologyManagerImportTest.java

  21 
vote

@Test public void testImportForNewlyAddedRSA() throws InterruptedException {
  IMocksControl c=EasyMock.createNiceControl();
  c.makeThreadSafe(true);
  final Semaphore sema=new Semaphore(0);
  BundleContext bc=c.createMock(BundleContext.class);
  ServiceRegistration sreg=c.createMock(ServiceRegistration.class);
  EasyMock.expect(bc.registerService((String)EasyMock.anyObject(),EasyMock.anyObject(),(Dictionary)EasyMock.anyObject())).andReturn(sreg).anyTimes();
  EndpointDescription epd=c.createMock(EndpointDescription.class);
  RemoteServiceAdmin rsa=c.createMock(RemoteServiceAdmin.class);
  final ImportRegistration ireg=c.createMock(ImportRegistration.class);
  ImportReference iref=c.createMock(ImportReference.class);
  EasyMock.expect(rsa.importService(EasyMock.eq(epd))).andAnswer(new IAnswer<ImportRegistration>(){
    public ImportRegistration answer() throws Throwable {
      sema.release();
      return ireg;
    }
  }
).once();
  EasyMock.expect(ireg.getImportReference()).andReturn(iref).anyTimes();
  EasyMock.expect(iref.getImportedEndpoint()).andReturn(epd).anyTimes();
  c.replay();
  RemoteServiceAdminList rsaList=new RemoteServiceAdminList(bc);
  TopologyManagerImport tm=new TopologyManagerImport(bc,rsaList);
  tm.start();
  tm.addImportableService("myFilter",epd);
  rsaList.add(rsa);
  tm.triggerExportImportForRemoteServiceAdmin(rsa);
  assertTrue(sema.tryAcquire(10,TimeUnit.SECONDS));
  tm.stop();
  c.verify();
}
 

Example 15

From project dmix, under directory /JmDNS/src/javax/jmdns/impl/.

Source file: DNSStatefulObject.java

  21 
vote

/** 
 * Blocks the current thread until the event arrives or the timeout expires.
 * @param timeout wait period for the event
 */
public void waitForEvent(long timeout){
  Thread thread=Thread.currentThread();
  Semaphore semaphore=_semaphores.get(thread);
  if (semaphore == null) {
    semaphore=new Semaphore(1,true);
    semaphore.drainPermits();
    _semaphores.putIfAbsent(thread,semaphore);
  }
  semaphore=_semaphores.get(thread);
  try {
    semaphore.tryAcquire(timeout,TimeUnit.MILLISECONDS);
  }
 catch (  InterruptedException exception) {
    logger.log(Level.FINER,"Exception ",exception);
  }
}
 

Example 16

From project encog-java-core, under directory /src/main/java/org/encog/util/.

Source file: ImageSize.java

  21 
vote

/** 
 * Determine the size of an image.
 * @param image The image to be sized.
 */
public ImageSize(final Image image){
  this.wait=new Semaphore(0);
  this.width=image.getWidth(this);
  this.height=image.getHeight(this);
  if ((this.width == -1) || (this.height == -1)) {
    try {
      this.wait.acquire();
    }
 catch (    final InterruptedException e) {
      throw new EncogError(e);
    }
  }
}
 

Example 17

From project external-replicaisland, under directory /src/com/replica/replicaisland/.

Source file: RenderingWatchDog.java

  21 
vote

/** 
 * start watch-dog 
 */
public void start(){
  Log.i(TAG,"start");
  mStopRequested=false;
  mSemaphore=new Semaphore(0);
  mThread=new Thread(this);
  mThread.start();
}
 

Example 18

From project FlipDroid, under directory /app/src/com/goal98/flipdroid2/activity/.

Source file: ArticleLoader.java

  21 
vote

public ArticleLoader(Activity activity,int articlePerPage,String from,String name,int inDaysFrom,int inDaysTo){
  this.activity=activity;
  this.name=name;
  PagingStrategy pagingStrategy=new FixedPagingStrategy(activity,articlePerPage);
  pagingStrategy.setNoMoreArticleListener(new NoMoreArticleListener(){
    public void onNoMoreArticle() throws NoMoreStatusException {
      throw new NoMoreStatusException();
    }
  }
);
  Semaphore refreshingSemaphore=new Semaphore(1,true);
  repo=new ContentRepo(pagingStrategy,refreshingSemaphore);
  rssurlDB=new RSSURLDB(activity);
  articleSource=new AllLocalArticleSource(rssurlDB,from,inDaysFrom,inDaysTo);
  repo.setArticleSource(articleSource);
  repo.setPagingStrategy(pagingStrategy);
}
 

Example 19

From project gecko, under directory /src/main/java/com/taobao/gecko/service/impl/.

Source file: DefaultRemotingContext.java

  21 
vote

public DefaultRemotingContext(final BaseConfig config,final CommandFactory commandFactory){
  this.groupManager=new GroupManager();
  this.config=config;
  if (commandFactory == null) {
    throw new IllegalArgumentException("CommandFactory????");
  }
  this.commandFactory=commandFactory;
  this.callBackSemaphore=new Semaphore(this.config.getMaxCallBackCount());
  MBeanUtils.registerMBeanWithIdPrefix(this,null);
}
 

Example 20

From project GSM-Signal-Tracking-, under directory /gpstracker/src/nl/sogeti/android/gpstracker/viewer/.

Source file: LoggerMap.java

  21 
vote

/** 
 * Called when the activity is first created.
 */
@Override protected void onCreate(Bundle load){
  super.onCreate(load);
  setContentView(R.layout.map);
  mLoggerServiceManager=new GPSLoggerServiceManager(this);
  final Semaphore calulatorSemaphore=new Semaphore(0);
  Thread calulator=new Thread("OverlayCalculator"){
    public void run(){
      Looper.prepare();
      mHandler=new Handler();
      calulatorSemaphore.release();
      Looper.loop();
    }
  }
;
  calulator.start();
  try {
    calulatorSemaphore.acquire();
  }
 catch (  InterruptedException e) {
    Log.e(TAG,"Failed waiting for a semaphore",e);
  }
  mUnits=new UnitsI18n(this,mUnitsChangeListener);
  mSharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);
  mSharedPreferences.registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);
  mMapView=new MapViewProxy();
  updateMapProvider();
  mMylocation=new MyLocationOverlayProxy(this,mMapView);
  mMapView.setBuiltInZoomControls(true);
  mMapView.setClickable(true);
  TextView[] speeds={(TextView)findViewById(R.id.speedview05),(TextView)findViewById(R.id.speedview04),(TextView)findViewById(R.id.speedview03),(TextView)findViewById(R.id.speedview02),(TextView)findViewById(R.id.speedview01),(TextView)findViewById(R.id.speedview00)};
  mSpeedtexts=speeds;
  mLastGPSSpeedView=(TextView)findViewById(R.id.currentSpeed);
  mLastGPSAltitudeView=(TextView)findViewById(R.id.currentAltitude);
  mLastSignalStrengthView=(TextView)findViewById(R.id.currentSignalStrength);
  onRestoreInstanceState(load);
}
 

Example 21

From project hawtdispatch, under directory /hawtdispatch-example/src/main/scala/org/fusesource/hawtdispatch/example/.

Source file: CustomDispatchSourceJava.java

  21 
vote

public static void run() throws Exception {
  final Semaphore done=new Semaphore(1 - (1000 * 1000));
  DispatchQueue queue=createQueue();
  final CustomDispatchSource<Integer,Integer> source=createSource(EventAggregators.INTEGER_ADD,queue);
  source.setEventHandler(new Task(){
    public void run(){
      int count=source.getData();
      System.out.println("got: " + count);
      done.release(count);
    }
  }
);
  source.resume();
  for (int i=0; i < 1000; i++) {
    getGlobalQueue().execute(new Task(){
      public void run(){
        for (int j=0; j < 1000; j++) {
          source.merge(1);
        }
      }
    }
);
  }
  done.acquire();
}
 

Example 22

From project heritrix3, under directory /commons/src/test/java/org/archive/util/.

Source file: ArchiveUtilsTest.java

  21 
vote

/** 
 * Test stable behavior of date formatting under heavy concurrency. 
 * @throws InterruptedException
 */
public static void testDateFormatConcurrency() throws InterruptedException {
  final int COUNT=1000;
  Thread[] ts=new Thread[COUNT];
  final Semaphore allDone=new Semaphore(-COUNT + 1);
  final AtomicInteger failures=new AtomicInteger(0);
  for (int i=0; i < COUNT; i++) {
    Thread t=new Thread(){
      public void run(){
        long n=System.currentTimeMillis();
        final String d=ArchiveUtils.get17DigitDate(n);
        for (int i=0; i < 1000; i++) {
          try {
            sleep(10);
          }
 catch (          InterruptedException e) {
            e.printStackTrace();
          }
          String d2=ArchiveUtils.get17DigitDate(n);
          if (!d.equals(d2)) {
            failures.incrementAndGet();
            break;
          }
        }
        allDone.release();
      }
    }
;
    ts[i]=t;
    ts[i].setName(Integer.toString(i));
    ts[i].start();
    while (!ts[i].isAlive())     ;
  }
  allDone.acquire();
  assertEquals(failures.get() + " format mismatches",0,failures.get());
}
 

Example 23

From project indextank-engine, under directory /src/main/java/com/flaptor/indextank/search/.

Source file: TrafficLimitingSearcher.java

  21 
vote

/** 
 * @param searcher the delegate DocumentSearcher
 * @param maxSearchQueueLength max allowed search queue length, or 0 for no waiters allowed
 */
public TrafficLimitingSearcher(DocumentSearcher searcher,int maxSearchQueueLength){
  Preconditions.checkNotNull(searcher);
  Preconditions.checkArgument(maxSearchQueueLength >= 0);
  this.delegate=searcher;
  this.maxSearchQueueLength=maxSearchQueueLength;
  semaphore=new Semaphore(MAX_NUMBER_OF_PARALLEL_REQUESTS,true);
}
 

Example 24

From project IOCipherServer, under directory /src/javax/jmdns/impl/.

Source file: DNSStatefulObject.java

  21 
vote

/** 
 * Blocks the current thread until the event arrives or the timeout expires.
 * @param timeout wait period for the event
 */
public void waitForEvent(long timeout){
  Thread thread=Thread.currentThread();
  Semaphore semaphore=_semaphores.get(thread);
  if (semaphore == null) {
    semaphore=new Semaphore(1,true);
    semaphore.drainPermits();
    _semaphores.putIfAbsent(thread,semaphore);
  }
  semaphore=_semaphores.get(thread);
  try {
    semaphore.tryAcquire(timeout,TimeUnit.MILLISECONDS);
  }
 catch (  InterruptedException exception) {
    logger.log(Level.FINER,"Exception ",exception);
  }
}
 

Example 25

From project JAirPort, under directory /src/javax/jmdns/impl/.

Source file: DNSStatefulObject.java

  21 
vote

/** 
 * Blocks the current thread until the event arrives or the timeout expires.
 * @param timeout wait period for the event
 */
public void waitForEvent(long timeout){
  Thread thread=Thread.currentThread();
  Semaphore semaphore=_semaphores.get(thread);
  if (semaphore == null) {
    semaphore=new Semaphore(1,true);
    semaphore.drainPermits();
    _semaphores.putIfAbsent(thread,semaphore);
  }
  semaphore=_semaphores.get(thread);
  try {
    semaphore.tryAcquire(timeout,TimeUnit.MILLISECONDS);
  }
 catch (  InterruptedException exception) {
    logger.log(Level.FINER,"Exception ",exception);
  }
}
 

Example 26

From project jena-tdb, under directory /src/main/java/com/hp/hpl/jena/tdb/store/bulkloader/.

Source file: BuilderSecondaryIndexesParallel.java

  21 
vote

@Override public void createSecondaryIndexes(TupleIndex primaryIndex,TupleIndex[] secondaryIndexes){
  monitor.print("** Parallel index building");
  Timer timer=new Timer();
  timer.startTimer();
  int semaCount=0;
  Semaphore sema=new Semaphore(0);
  for (  TupleIndex index : secondaryIndexes) {
    if (index != null) {
      Runnable builder=setup(sema,primaryIndex,index,index.getMapping());
      new Thread(builder).start();
      semaCount++;
    }
  }
  try {
    sema.acquire(semaCount);
  }
 catch (  InterruptedException ex) {
    ex.printStackTrace();
  }
  long time=timer.readTimer();
  timer.endTimer();
  monitor.print("Time for parallel indexing: %.2fs\n",time / 1000.0);
}
 

Example 27

From project magrit, under directory /server/core/src/main/java/org/kercoin/magrit/core/build/pipeline/.

Source file: PipelineImpl.java

  21 
vote

@Inject public PipelineImpl(Context ctx){
  log.info("{} cores",ctx.configuration().getSlots());
  slots=new Semaphore(ctx.configuration().getSlots());
  tasks=new ConcurrentHashMap<Key,Task<BuildResult>>();
  futures=new ConcurrentHashMap<Key,Future<BuildResult>>();
  workings=Collections.newSetFromMap(new ConcurrentHashMap<Key,Boolean>());
  dispatcher=new DispatcherThreadPool(ctx.configuration().getSlots(),new PriorityBlockingQueue<Runnable>());
  addListener(accumulator);
}
 

Example 28

From project mcore, under directory /src/com/massivecraft/mcore4/xlib/mongodb/.

Source file: DBPortPool.java

  21 
vote

DBPortPool(ServerAddress addr,MongoOptions options){
  super("DBPortPool-" + addr.toString() + ", options = "+ options.toString(),options.connectionsPerHost,options.connectionsPerHost);
  _options=options;
  _addr=addr;
  _waitingSem=new Semaphore(_options.connectionsPerHost * _options.threadsAllowedToBlockForConnectionMultiplier);
}
 

Example 29

From project MeQanTT, under directory /mqtt-library/src/main/java/org/meqantt/.

Source file: SocketClient.java

  21 
vote

public void connect(String host,int port) throws UnknownHostException, IOException, InterruptedException {
  socket=new Socket(host,port);
  InputStream is=socket.getInputStream();
  in=new MessageInputStream(is);
  OutputStream os=socket.getOutputStream();
  out=new MessageOutputStream(os);
  reader=new MqttReader();
  reader.start();
  ConnectMessage msg=new ConnectMessage(id,false,60);
  connectionAckLock=new Semaphore(0);
  out.writeMessage(msg);
  connectionAckLock.acquire();
}
 

Example 30

From project mongo-java-driver, under directory /src/main/com/mongodb/.

Source file: DBPortPool.java

  21 
vote

DBPortPool(ServerAddress addr,MongoOptions options){
  super("DBPortPool-" + addr.toString() + ", options = "+ options.toString(),options.connectionsPerHost);
  _options=options;
  _addr=addr;
  _waitingSem=new Semaphore(_options.connectionsPerHost * _options.threadsAllowedToBlockForConnectionMultiplier);
}
 

Example 31

From project mustache.java, under directory /compiler/src/test/java/com/github/mustachejavabenchmarks/.

Source file: JsonInterpreterTest.java

  21 
vote

public void testMultithreaded() throws IOException, InterruptedException {
  if (skip())   return;
  final Mustache parse=getMustache();
  final Object parent=getScope();
  final AtomicInteger runs=new AtomicInteger(0);
  ExecutorService es=Executors.newCachedThreadPool();
  int range=(int)Math.round(Runtime.getRuntime().availableProcessors() * 1.5 + 1);
  for (int threads=1; threads < range; threads++) {
    final Semaphore semaphore=new Semaphore(threads);
{
      long start=System.currentTimeMillis();
      while (true) {
        semaphore.acquire();
        es.submit(new Runnable(){
          @Override public void run(){
            parse.execute(new NullWriter(),new Object[]{parent});
            runs.incrementAndGet();
            semaphore.release();
          }
        }
);
        if (System.currentTimeMillis() - start > TIME * 1000) {
          break;
        }
      }
      System.out.println("NullWriter Serial with " + threads + " threads: "+ runs.intValue() / TIME + "/s " + " per thread: " + (runs.intValue() / TIME / threads));
      runs.set(0);
      Thread.sleep(100);
    }
  }
}
 

Example 32

From project opencit, under directory /core/projectmanager/src/test/java/org/openengsb/opencit/core/projectmanager/internal/.

Source file: ProjectManagerImplTest.java

  21 
vote

@Test 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("ci")).thenReturn(1L);
  doAnswer(new Answer<Void>(){
    @Override 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));
}
 

Example 33

From project packages_apps_Calendar, under directory /tests/src/com/android/calendar/.

Source file: AsyncQueryServiceTest.java

  21 
vote

public TestAsyncQueryService(Context context,OperationInfo[] work){
  super(context);
  mCountingSemaphore=new Semaphore(0);
  HandlerThread thread=new HandlerThread("TestAsyncQueryService");
  thread.start();
  super.setTestHandler(new Handler(thread.getLooper()){
    @Override public void handleMessage(    Message msg){
      TestAsyncQueryService.this.handleMessage(msg);
    }
  }
);
  mWork=work;
}
 

Example 34

From project platform_packages_apps_calendar, under directory /tests/src/com/android/calendar/.

Source file: AsyncQueryServiceTest.java

  21 
vote

public TestAsyncQueryService(Context context,OperationInfo[] work){
  super(context);
  mCountingSemaphore=new Semaphore(0);
  HandlerThread thread=new HandlerThread("TestAsyncQueryService");
  thread.start();
  super.setTestHandler(new Handler(thread.getLooper()){
    @Override public void handleMessage(    Message msg){
      TestAsyncQueryService.this.handleMessage(msg);
    }
  }
);
  mWork=work;
}
 

Example 35

From project Racenet-for-Android, under directory /src/com/albin/mqtt/.

Source file: SocketClient.java

  21 
vote

public void connect(String host,int port) throws UnknownHostException, IOException, InterruptedException {
  socket=new Socket(host,port);
  InputStream is=socket.getInputStream();
  in=new MessageInputStream(is);
  OutputStream os=socket.getOutputStream();
  out=new MessageOutputStream(os);
  reader=new MqttReader();
  reader.start();
  ConnectMessage msg=new ConnectMessage(id,false,60);
  connectionAckLock=new Semaphore(0);
  out.writeMessage(msg);
  connectionAckLock.acquire();
}
 

Example 36

From project rascal-eclipse, under directory /src/org/rascalmpl/eclipse/console/internal/.

Source file: TimedBufferedPipe.java

  21 
vote

public TimedBufferedPipe(long interval,PausableOutput target,String name){
  this.target=target;
  syncer=null;
  flushStream=new Semaphore(1);
  streamFlushed=new Semaphore(8);
  this.name=name;
  this.interval=interval;
}
 

Example 37

From project Red5, under directory /src/org/red5/server/net/rtmp/.

Source file: RTMPMinaConnection.java

  21 
vote

/** 
 * {@inheritDoc} 
 */
@Override public void write(Packet out){
  if (ioSession != null) {
    final Semaphore lock=getLock();
    log.trace("Write lock wait count: {}",lock.getQueueLength());
    while (!closed) {
      try {
        lock.acquire();
      }
 catch (      InterruptedException e) {
        log.warn("Interrupted while waiting for write lock",e);
        continue;
      }
      try {
        log.debug("Writing message");
        writingMessage(out);
        ioSession.write(out);
        break;
      }
  finally {
        lock.release();
      }
    }
  }
}
 

Example 38

From project spring-batch-admin, under directory /spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/util/.

Source file: ThrottledTaskExecutor.java

  21 
vote

/** 
 * Create a  {@link ThrottledTaskExecutor} with finite throttlelimit. The submit method will block when this limit is reached until one of the tasks has finished.
 * @param taskExecutor the {@link TaskExecutor} to use
 * @param throttleLimit the throttle limit
 */
public ThrottledTaskExecutor(TaskExecutor taskExecutor,int throttleLimit){
  super();
  if (taskExecutor != null) {
    this.taskExecutor=taskExecutor;
  }
  this.semaphore=new Semaphore(throttleLimit);
}
 

Example 39

From project thymeleaf, under directory /src/main/java/org/thymeleaf/util/.

Source file: ResourcePool.java

  21 
vote

public ResourcePool(final Collection<T> resources){
  super();
  Validate.notNull(resources,"Resources for pool cannot be null");
  this.pool=new LinkedList<T>(resources);
  this.allocated=new HashSet<T>(this.pool.size() + 1,1.0f);
  this.semaphore=new Semaphore(this.pool.size());
  this.resourceFactory=null;
}
 

Example 40

From project TomP2P, under directory /src/main/java/net/tomp2p/connection/.

Source file: ChannelCreator.java

  21 
vote

/** 
 * Package private constructor, since this is created by  {@link ConnectionReservation} and should never be calleddirectly.
 * @param permits The number of max. parallel connections.
 * @param statistics The class that counts the created TCP and UDP connections.
 * @param messageLoggerFilter
 * @param tcpClientChannelFactory
 * @param udpClientChannelFactory
 * @param keepAliveAndReuse
 */
ChannelCreator(int permits,Statistics statistics,MessageLogger messageLoggerFilter,ChannelFactory tcpClientChannelFactory,ChannelFactory udpClientChannelFactory,boolean keepAliveAndReuse,String name,long creatorThread,Scheduler scheduler){
  this.permitsCount=new AtomicInteger(permits);
  this.connectionSemaphore=new Semaphore(permits);
  this.cacheMap=new ConcurrentHashMap<InetSocketAddress,ChannelFuture>(permits);
  this.messageLoggerFilter=messageLoggerFilter;
  this.tcpClientChannelFactory=tcpClientChannelFactory;
  this.udpChannelFactory=udpClientChannelFactory;
  this.keepAliveAndReuse=keepAliveAndReuse;
  this.statistics=statistics;
  this.channelCreatorName=name;
  this.creatorThread=creatorThread;
  this.permits=permits;
  this.scheduler=scheduler;
}
 

Example 41

From project torquebox, under directory /modules/core/src/main/java/org/torquebox/core/pool/.

Source file: PoolManager.java

  21 
vote

public void start(){
  started=true;
  this.instances=new Semaphore(this.maxInstances - this.minInstances,true);
  if (this.executor == null) {
    this.executor=Executors.newFixedThreadPool(4);
  }
  for (int i=0; i < this.minInstances; ++i) {
    this.executor.execute(this.fillTask);
  }
}
 

Example 42

From project TransFile, under directory /tests/net/sourceforge/transfile/operations/.

Source file: DummyConnectionTest.java

  21 
vote

/** 
 * TODO doc
 * @param executor <br>Should not be null <br>Input-output
 * @param timeout in milliseconds<br>Range:  {@code [0 .. Long.MAX_VALUE]}
 */
public static final void waitUntilExecutorIsReady(final Executor executor,final long timeout){
  try {
    final Semaphore semaphore=new Semaphore(0);
    executor.execute(new Runnable(){
      @Override public final void run(){
        semaphore.release();
      }
    }
);
    assertTrue(semaphore.tryAcquire(timeout,TimeUnit.MILLISECONDS));
  }
 catch (  final InterruptedException exception) {
    exception.printStackTrace();
  }
}
 

Example 43

From project WaarpCommon, under directory /src/main/java/org/waarp/common/database/.

Source file: DbConnectionPool.java

  21 
vote

/** 
 * Constructs a ConnectionPool object.
 * @param dataSource the data source for the connections.
 * @param maxConnections the maximum number of connections. 0 means no limit
 * @param timeout the maximum time in seconds to wait for a free connection.
 */
public DbConnectionPool(ConnectionPoolDataSource dataSource,int maxConnections,int timeout){
  this.dataSource=dataSource;
  this.maxConnections=maxConnections;
  this.timeout=timeout;
  if (maxConnections != 0) {
    if (timeout <= 0) {
      throw new IllegalArgumentException("Invalid timeout value.");
    }
    semaphore=new Semaphore(maxConnections,true);
  }
  recycledConnections=new ArrayDeque<Con>();
  poolConnectionEventListener=new PoolConnectionEventListener();
}
 

Example 44

From project zanata, under directory /zanata-war/src/main/java/org/zanata/process/.

Source file: IterationZipFileBuildProcessHandle.java

  21 
vote

public IterationZipFileBuildProcessHandle(){
  this.readySemaphore=new Semaphore(1);
  try {
    this.readySemaphore.acquire();
  }
 catch (  InterruptedException e) {
  }
}
 

Example 45

From project zeroconf_implementations, under directory /zeroconf_jmdns/src/main/java/javax/jmdns/impl/.

Source file: DNSStatefulObject.java

  21 
vote

/** 
 * Blocks the current thread until the event arrives or the timeout expires.
 * @param timeout wait period for the event
 */
public void waitForEvent(long timeout){
  Thread thread=Thread.currentThread();
  Semaphore semaphore=_semaphores.get(thread);
  if (semaphore == null) {
    semaphore=new Semaphore(1,true);
    semaphore.drainPermits();
    _semaphores.putIfAbsent(thread,semaphore);
  }
  semaphore=_semaphores.get(thread);
  try {
    semaphore.tryAcquire(timeout,TimeUnit.MILLISECONDS);
  }
 catch (  InterruptedException exception) {
    logger.log(Level.FINER,"Exception ",exception);
  }
}
 

Example 46

From project AdServing, under directory /modules/utilities/common/src/main/java/biz/source_code/miniConnectionPoolManager/.

Source file: MiniConnectionPoolManager.java

  20 
vote

/** 
 * Constructs a MiniConnectionPoolManager object.
 * @param dataSource the data source for the connections.
 * @param maxConnections the maximum number of connections.
 * @param timeout the maximum time in seconds to wait for a free connection.
 */
public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource,int maxConnections,int timeout){
  this.dataSource=dataSource;
  this.maxConnections=maxConnections;
  this.timeoutMs=timeout * 1000L;
  try {
    logWriter=dataSource.getLogWriter();
  }
 catch (  SQLException e) {
  }
  if (maxConnections < 1) {
    throw new IllegalArgumentException("Invalid maxConnections value.");
  }
  semaphore=new Semaphore(maxConnections,true);
  recycledConnections=new LinkedList<PooledConnection>();
  poolConnectionEventListener=new PoolConnectionEventListener();
}
 

Example 47

From project authme-2.0, under directory /src/uk/org/whoami/authme/datasource/.

Source file: MiniConnectionPoolManager.java

  20 
vote

/** 
 * Constructs a MiniConnectionPoolManager object.
 * @param dataSource the data source for the connections.
 * @param maxConnections the maximum number of connections.
 * @param timeout the maximum time in seconds to wait for a free connection.
 */
public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource,int maxConnections,int timeout){
  this.dataSource=dataSource;
  this.maxConnections=maxConnections;
  this.timeoutMs=timeout * 1000L;
  try {
    logWriter=dataSource.getLogWriter();
  }
 catch (  SQLException e) {
  }
  if (maxConnections < 1) {
    throw new IllegalArgumentException("Invalid maxConnections value.");
  }
  semaphore=new Semaphore(maxConnections,true);
  recycledConnections=new LinkedList<PooledConnection>();
  poolConnectionEventListener=new PoolConnectionEventListener();
}
 

Example 48

From project AuthMe-Reloaded, under directory /src/main/java/uk/org/whoami/authme/datasource/.

Source file: MiniConnectionPoolManager.java

  20 
vote

/** 
 * Constructs a MiniConnectionPoolManager object.
 * @param dataSource the data source for the connections.
 * @param maxConnections the maximum number of connections.
 * @param timeout the maximum time in seconds to wait for a free connection.
 */
public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource,int maxConnections,int timeout){
  this.dataSource=dataSource;
  this.maxConnections=maxConnections;
  this.timeoutMs=timeout * 1000L;
  try {
    logWriter=dataSource.getLogWriter();
  }
 catch (  SQLException e) {
  }
  if (maxConnections < 1) {
    throw new IllegalArgumentException("Invalid maxConnections value.");
  }
  semaphore=new Semaphore(maxConnections,true);
  recycledConnections=new LinkedList<PooledConnection>();
  poolConnectionEventListener=new PoolConnectionEventListener();
}
 

Example 49

From project AuthMe-Reloaded-Charge-fix, under directory /src/uk/org/whoami/authme/datasource/.

Source file: MiniConnectionPoolManager.java

  20 
vote

/** 
 * Constructs a MiniConnectionPoolManager object.
 * @param dataSource the data source for the connections.
 * @param maxConnections the maximum number of connections.
 * @param timeout the maximum time in seconds to wait for a free connection.
 */
public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource,int maxConnections,int timeout){
  this.dataSource=dataSource;
  this.maxConnections=maxConnections;
  this.timeoutMs=timeout * 1000L;
  try {
    logWriter=dataSource.getLogWriter();
  }
 catch (  SQLException e) {
  }
  if (maxConnections < 1) {
    throw new IllegalArgumentException("Invalid maxConnections value.");
  }
  semaphore=new Semaphore(maxConnections,true);
  recycledConnections=new LinkedList<PooledConnection>();
  poolConnectionEventListener=new PoolConnectionEventListener();
}
 

Example 50

From project flume, under directory /flume-ng-channels/flume-recoverable-memory-channel/src/main/java/org/apache/flume/channel/recoverable/memory/.

Source file: RecoverableMemoryChannel.java

  20 
vote

@Override public void configure(Context context){
  memoryChannel.configure(context);
  int capacity=context.getInteger(CAPACITY,DEFAULT_CAPACITY);
  if (queueRemaining == null) {
    queueRemaining=new Semaphore(capacity,true);
  }
 else   if (capacity > this.capacity) {
    queueRemaining.release(capacity - this.capacity);
  }
 else   if (capacity < this.capacity) {
    queueRemaining.acquireUninterruptibly(this.capacity - capacity);
  }
  this.capacity=capacity;
  keepAlive=context.getInteger(KEEPALIVE,DEFAULT_KEEPALIVE);
  long rollSize=context.getLong(WAL_ROLL_SIZE,WAL.DEFAULT_ROLL_SIZE);
  long maxLogsSize=context.getLong(WAL_MAX_LOGS_SIZE,WAL.DEFAULT_MAX_LOGS_SIZE);
  long minLogRetentionPeriod=context.getLong(WAL_MIN_RETENTION_PERIOD,WAL.DEFAULT_MIN_LOG_RETENTION_PERIOD);
  long workerInterval=context.getLong(WAL_WORKER_INTERVAL,WAL.DEFAULT_WORKER_INTERVAL);
  if (wal == null) {
    String homePath=System.getProperty("user.home").replace('\\','/');
    String dataDir=context.getString(WAL_DATA_DIR,homePath + "/.flume/recoverable-memory-channel");
    try {
      wal=new WAL<RecoverableMemoryChannelEvent>(new File(dataDir),RecoverableMemoryChannelEvent.class,rollSize,maxLogsSize,minLogRetentionPeriod,workerInterval);
    }
 catch (    IOException e) {
      Throwables.propagate(e);
    }
  }
 else {
    wal.setRollSize(rollSize);
    wal.setMaxLogsSize(maxLogsSize);
    wal.setMinLogRetentionPeriod(minLogRetentionPeriod);
    wal.setWorkerInterval(workerInterval);
    LOG.warn(this.getClass().getSimpleName() + " only supports " + "partial reconfiguration.");
  }
}
 

Example 51

From project iPage, under directory /src/test/java/com/github/zhongl/api/.

Source file: EphemeronsTest.java

  20 
vote

@Before public void setUp() throws Exception {
  store=new Store();
  mergeBefore=new Semaphore(0);
  mergeAfter=new Semaphore(0);
  ephemerons=new Ephemerons<Integer>(){
    @Override protected void requestFlush(    final Collection<WriteOperation<Entry<Key,Integer>>> addOrUpdates,    final Collection<WriteOperation<Key>> removes,    final FutureCallback<Void> futureCallback){
      new Thread(new Runnable(){
        @Override public void run(){
          mergeBefore.release();
          store.merge(addOrUpdates,removes,futureCallback);
          mergeAfter.release();
        }
      }
).start();
    }
    @Override protected Integer getMiss(    Key key){
      return store.get(key);
    }
  }
;
  ignore=FutureCallbacks.ignore();
}
 

Example 52

From project jboss-ejb-client, under directory /src/main/java/org/jboss/ejb/client/remoting/.

Source file: ChannelAssociation.java

  20 
vote

/** 
 * Creates a channel association for the passed  {@link EJBReceiverContext} and the {@link Channel}
 * @param ejbReceiver        The EJB receiver
 * @param ejbReceiverContext The receiver context
 * @param channel            The channel that will be used for remoting communication
 * @param protocolVersion    The protocol version
 * @param marshallerFactory  The marshalling factory
 * @param reconnectHandler   The reconnect handler to use for broken connections/channels. Can be null.
 */
ChannelAssociation(final RemotingConnectionEJBReceiver ejbReceiver,final EJBReceiverContext ejbReceiverContext,final Channel channel,final byte protocolVersion,final MarshallerFactory marshallerFactory,final ReconnectHandler reconnectHandler){
  this.ejbReceiver=ejbReceiver;
  this.ejbReceiverContext=ejbReceiverContext;
  this.channel=channel;
  this.protocolVersion=protocolVersion;
  this.marshallerFactory=marshallerFactory;
  this.reconnectHandler=reconnectHandler;
  this.channel.addCloseHandler(new CloseHandler<Channel>(){
    @Override public void handleClose(    Channel closed,    IOException exception){
      logger.debug("Closing channel " + closed,exception);
      if (exception != null) {
        ChannelAssociation.this.notifyBrokenChannel(exception);
      }
 else {
        ChannelAssociation.this.notifyBrokenChannel(new IOException("Channel " + closed + " has been closed"));
      }
    }
  }
);
  this.channel.receiveMessage(new ResponseReceiver());
  Integer maxOutboundWrites=this.channel.getOption(RemotingOptions.MAX_OUTBOUND_MESSAGES);
  if (maxOutboundWrites == null) {
    maxOutboundWrites=80;
  }
  this.channelWriteSemaphore=new Semaphore(maxOutboundWrites,true);
}
 

Example 53

From project mapfish-print, under directory /src/main/java/org/mapfish/print/output/.

Source file: NativeProcessOutputFactory.java

  20 
vote

public NativeProcessOutputFactory(int maxProcesses){
  runningProcesses=new Semaphore(maxProcesses,true);
  if (java.lang.management.ManagementFactory.getOperatingSystemMXBean().getName().toLowerCase().contains("win")) {
    cmd="convert";
  }
 else {
    cmd="/usr/bin/convert";
  }
  cmdArgs.add("-density");
  cmdArgs.add("${dpi}x${dpi}");
  cmdArgs.add("-append");
  cmdArgs.add("${sourceFile}");
  cmdArgs.add("${targetFile}");
  formats.add("jpg");
  formats.add("gif");
  formats.add("png");
  formats.add("bmp");
  formats.add("tif");
  formats.add("tiff");
}
 

Example 54

From project rabbitmq-java-client, under directory /test/src/com/rabbitmq/examples/perf/.

Source file: Producer.java

  20 
vote

public Producer(Channel channel,String exchangeName,String id,List<?> flags,int txSize,int rateLimit,int msgLimit,int minMsgSize,int timeLimit,long confirm,Stats stats) throws IOException {
  this.channel=channel;
  this.exchangeName=exchangeName;
  this.id=id;
  this.mandatory=flags.contains("mandatory");
  this.immediate=flags.contains("immediate");
  this.persistent=flags.contains("persistent");
  this.txSize=txSize;
  this.rateLimit=rateLimit;
  this.msgLimit=msgLimit;
  this.timeLimit=1000L * timeLimit;
  this.message=new byte[minMsgSize];
  if (confirm > 0) {
    this.confirmPool=new Semaphore((int)confirm);
  }
  this.stats=stats;
}
 

Example 55

From project s12gx.2011, under directory /src/test/java/org/springone2gx_2011/integration/resequencer/.

Source file: ResequencerDemo.java

  20 
vote

public void process(final Integer payload,final @Header(MessageHeaders.CORRELATION_ID) Object correlationId) throws Exception {
  locks.putIfAbsent(correlationId,new Semaphore(1,true));
  this.taskExecutor.execute(new Runnable(){
    public void run(){
      try {
        locks.get(correlationId).acquire();
        System.out.println("Processing: " + payload + " correlationId: "+ correlationId);
        Thread.sleep(random.nextInt(2000));
        locks.get(correlationId).release();
      }
 catch (      Exception e) {
        e.printStackTrace();
      }
    }
  }
);
}
 

Example 56

From project AndroidLab, under directory /libs/unboundid/docs/examples/.

Source file: SearchRateAsyncListener.java

  19 
vote

/** 
 * Creates a new instance of this listener with the provided information.
 * @param searchCounter    A value that will be used to keep track of thetotal number of searches performed.
 * @param entryCounter     A value that will be used to keep track of thetotal number of entries returned.
 * @param searchDurations  A value that will be used to keep track of thetotal duration for all searches.
 * @param errorCounter     A value that will be used to keep track of thenumber of errors encountered while searching.
 * @param rcCounter        The result code counter to use for keeping trackof the result codes for failed operations.
 * @param asyncSemaphore   The semaphore used ot limit the total number ofoutstanding asynchronous requests.
 * @param resultCode       The result code for the search thread.
 */
SearchRateAsyncListener(final AtomicLong searchCounter,final AtomicLong entryCounter,final AtomicLong searchDurations,final AtomicLong errorCounter,final ResultCodeCounter rcCounter,final Semaphore asyncSemaphore,final AtomicReference<ResultCode> resultCode){
  this.searchCounter=searchCounter;
  this.entryCounter=entryCounter;
  this.searchDurations=searchDurations;
  this.errorCounter=errorCounter;
  this.rcCounter=rcCounter;
  this.asyncSemaphore=asyncSemaphore;
  this.resultCode=resultCode;
  startTime=System.nanoTime();
}
 

Example 57

From project azkaban, under directory /azkaban/src/java/azkaban/jobcontrol/impl/jobs/locks/.

Source file: PermitLock.java

  19 
vote

public PermitLock(String permitName,Semaphore permitPool,int numPermits,int totalPermits){
  _permitPool=permitPool;
  _totalPermits=totalPermits;
  _numPermits=numPermits;
  _permitName=permitName;
}
 

Example 58

From project examples_1, under directory /gateway/gateway.cli/src/com/example/gateway/cli/.

Source file: GatewayTestCLI.java

  19 
vote

private ServiceRegistration registerListener(String name,final Semaphore connected,final Semaphore testComplete,List<Collection<QuoteRequest>> requests,final boolean verbose){
  Hashtable<String,String> props=new Hashtable<String,String>();
  props.put(GatewayClient.ID,name);
  props.put("service.exported.interfaces","*");
  final HashSet<Object> ids=new HashSet<Object>();
  for (  Collection<QuoteRequest> batch : requests) {
    for (    QuoteRequest r : batch) {
      ids.add(r.getId());
    }
  }
  GatewayClient client=new GatewayClient(){
    public void receive(    Collection<Message> messages){
synchronized (ids) {
        for (        Message m : messages) {
          if (m instanceof Connection) {
            if (verbose) {
              System.out.println("Connected");
            }
            connected.release();
          }
 else {
            if (verbose) {
              System.out.println("Received " + m);
            }
            ids.remove(m.getId());
          }
        }
        if (ids.isEmpty()) {
          testComplete.release();
        }
      }
    }
  }
;
  return ctx.registerService(GatewayClient.class.getName(),client,props);
}
 

Example 59

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/lock/semaphore/.

Source file: SemaphoreLockManager.java

  19 
vote

private synchronized ReadWriteLock getReadWriteLock(String object){
  String key=(object != null) ? object : "";
  ReadWriteLock lock=this.lockMap.get(key);
  if (lock == null) {
    lock=new SemaphoreReadWriteLock(new Semaphore(Integer.MAX_VALUE,this.fair));
    ReadWriteLock existing=this.lockMap.putIfAbsent(key,lock);
    if (existing != null) {
      lock=existing;
    }
  }
  return lock;
}
 

Example 60

From project joshua, under directory /src/joshua/metrics/.

Source file: TercomRunner.java

  19 
vote

public TercomRunner(Semaphore in_blocker,String in_refFileName,String in_hypFileName,String in_outFileNamePrefix,int in_memSize){
  blocker=in_blocker;
  refFileName=in_refFileName;
  hypFileName=in_hypFileName;
  outFileNamePrefix=in_outFileNamePrefix;
  memSize=in_memSize;
}