示例#1
0
 /** remainingCapacity() always returns Integer.MAX_VALUE */
 public void testRemainingCapacity() {
   BlockingQueue q = populatedQueue(SIZE);
   for (int i = 0; i < SIZE; ++i) {
     assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
     assertEquals(SIZE - i, q.size());
     assertTrue(q.remove() instanceof PDelay);
   }
   for (int i = 0; i < SIZE; ++i) {
     assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
     assertEquals(i, q.size());
     assertTrue(q.add(new PDelay(i)));
   }
 }
 /**
  * Append a message to the list. If the list is full, the first message will be popped off of it.
  *
  * @param m log to be inserted
  */
 public synchronized void appendMessage(final LogCatMessage m) {
   if (mQ.remainingCapacity() == 0) {
     /* make space by removing the first entry */
     mQ.poll();
   }
   mQ.offer(m);
 }
 /**
  * Actual writing occurs here.
  *
  * @param logEvent The LogEvent.
  */
 @Override
 public void append(LogEvent logEvent) {
   if (!isStarted()) {
     throw new IllegalStateException("AsyncAppender " + getName() + " is not active");
   }
   if (!(logEvent instanceof Log4jLogEvent)) {
     if (!(logEvent instanceof RingBufferLogEvent)) {
       return; // only know how to Serialize Log4jLogEvents and RingBufferLogEvents
     }
     logEvent = ((RingBufferLogEvent) logEvent).createMemento();
   }
   logEvent.getMessage().getFormattedMessage(); // LOG4J2-763: ask message to freeze parameters
   final Log4jLogEvent coreEvent = (Log4jLogEvent) logEvent;
   boolean appendSuccessful = false;
   if (blocking) {
     if (isAppenderThread.get() == Boolean.TRUE && queue.remainingCapacity() == 0) {
       // LOG4J2-485: avoid deadlock that would result from trying
       // to add to a full queue from appender thread
       coreEvent.setEndOfBatch(false); // queue is definitely not empty!
       appendSuccessful = thread.callAppenders(coreEvent);
     } else {
       final Serializable serialized = Log4jLogEvent.serialize(coreEvent, includeLocation);
       try {
         // wait for free slots in the queue
         queue.put(serialized);
         appendSuccessful = true;
       } catch (final InterruptedException e) {
         // LOG4J2-1049: Some applications use Thread.interrupt() to send
         // messages between application threads. This does not necessarily
         // mean that the queue is full. To prevent dropping a log message,
         // quickly try to offer the event to the queue again.
         // (Yes, this means there is a possibility the same event is logged twice.)
         //
         // Finally, catching the InterruptedException means the
         // interrupted flag has been cleared on the current thread.
         // This may interfere with the application's expectation of
         // being interrupted, so when we are done, we set the interrupted
         // flag again.
         appendSuccessful = queue.offer(serialized);
         if (!appendSuccessful) {
           LOGGER.warn(
               "Interrupted while waiting for a free slot in the AsyncAppender LogEvent-queue {}",
               getName());
         }
         // set the interrupted flag again.
         Thread.currentThread().interrupt();
       }
     }
   } else {
     appendSuccessful = queue.offer(Log4jLogEvent.serialize(coreEvent, includeLocation));
     if (!appendSuccessful) {
       error("Appender " + getName() + " is unable to write primary appenders. queue is full");
     }
   }
   if (!appendSuccessful && errorAppender != null) {
     errorAppender.callAppender(coreEvent);
   }
 }
示例#4
0
    @TruffleBoundary
    @Specialization
    public int max(DynamicObject self) {
      final BlockingQueue<Object> queue = Layouts.SIZED_QUEUE.getQueue(self);

      // TODO (eregon, 12 July 2015): We could be more accurate here and remember the capacity
      // ourselves
      return queue.size() + queue.remainingCapacity();
    }
示例#5
0
 private void onEnd(WorkflowExecutionContext context) {
   if (Boolean.parseBoolean(ENABLE_POSTPROCESSING)) {
     return;
   }
   while (0 < blockingQueue.remainingCapacity()) {
     try {
       LOG.trace("Sleeping, no capacity in threadpool....");
       TimeUnit.MILLISECONDS.sleep(500);
     } catch (InterruptedException e) {
       LOG.error("Exception in LogMoverService", e);
     }
   }
   executorService.execute(new LogMover(context));
 }
示例#6
0
  public synchronized void runModel(Runnable model) {
    // Wait for space to open up in the queue
    while (tasks.remainingCapacity() < 1) {
      try {
        Thread.sleep(10);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }

    ThreadPoolHelper helper = new ThreadPoolHelper(model);

    threadPool.submit(helper);
  }
 /**
  * Return connection
  *
  * @param connection connection to return to the pool
  */
 public final void release(Connection connection) {
   if (connection != null) {
     try {
       connections.put(connection);
       logger.info("Connection " + connection + " returned to connection pool");
       logger.info(
           "There are "
               + (connections.size() - connections.remainingCapacity())
               + " connections in the pool.");
     } catch (InterruptedException e) {
       logger.error(e.getMessage());
     }
   }
 }
示例#8
0
    public String format(long timestamp) {
      SimpleDateFormat format = m_queue.poll();

      if (format == null) {
        format = new SimpleDateFormat(DATE_PATTERN);
      }

      try {
        return format.format(new Date(timestamp));
      } finally {
        if (m_queue.remainingCapacity() > 0) {
          m_queue.offer(format);
        }
      }
    }
示例#9
0
  // 生产者消费者模式,生产和消费URL
  public void push(String url) {
    if (unProcQueue.remainingCapacity() == 0) {
      System.out.println(Thread.currentThread().getName() + ": request queue is full...");
    }

    // 判断URL是否重复

    try {
      unProcQueue.put(url);
      System.out.println(
          Thread.currentThread().getName() + ": push website:" + url + " to request queue.");
      // System.out.println("push url to unProcQueue...");
    } catch (InterruptedException ie) {
      ie.printStackTrace();
    }
  }
示例#10
0
    public long parse(String str) {
      SimpleDateFormat format = m_queue.poll();

      if (format == null) {
        format = new SimpleDateFormat(DATE_PATTERN);
      }

      try {
        return format.parse(str).getTime();
      } catch (ParseException e) {
        return -1;
      } finally {
        if (m_queue.remainingCapacity() > 0) {
          m_queue.offer(format);
        }
      }
    }
  public void testDefaults() throws Exception {
    ConnectionFactory f = b.build();
    assertEquals(DefaultConnectionFactory.DEFAULT_OPERATION_TIMEOUT, f.getOperationTimeout());
    assertEquals(DefaultConnectionFactory.DEFAULT_READ_BUFFER_SIZE, f.getReadBufSize());
    assertSame(DefaultConnectionFactory.DEFAULT_HASH, f.getHashAlg());
    assertTrue(f.getDefaultTranscoder() instanceof SerializingTranscoder);
    assertSame(DefaultConnectionFactory.DEFAULT_FAILURE_MODE, f.getFailureMode());
    assertEquals(0, f.getInitialObservers().size());
    assertTrue(f.getOperationFactory() instanceof AsciiOperationFactory);

    BlockingQueue<Operation> opQueue = f.createOperationQueue();
    assertTrue(opQueue instanceof ArrayBlockingQueue<?>);
    assertEquals(DefaultConnectionFactory.DEFAULT_OP_QUEUE_LEN, opQueue.remainingCapacity());

    BlockingQueue<Operation> readOpQueue = f.createReadOperationQueue();
    assertTrue(readOpQueue instanceof LinkedBlockingQueue<?>);

    BlockingQueue<Operation> writeOpQueue = f.createWriteOperationQueue();
    assertTrue(writeOpQueue instanceof LinkedBlockingQueue<?>);

    MemcachedNode n = (MemcachedNode) mock(MemcachedNode.class).proxy();
    assertTrue(f.createLocator(Collections.singletonList(n)) instanceof ArrayModNodeLocator);

    final MemcachedNode testNode =
        f.createMemcachedNode(
            InetSocketAddress.createUnresolved("localhost", TestConfig.PORT_NUMBER), 1);
    try {
      assertTrue(testNode instanceof AsciiMemcachedNodeImpl);
    } finally {
      testNode.getChannel().close();
    }

    assertFalse(f.isDaemon());
    assertFalse(f.shouldOptimize());
    assertFalse(f.useNagleAlgorithm());
    assertEquals(
        f.getOpQueueMaxBlockTime(), DefaultConnectionFactory.DEFAULT_OP_QUEUE_MAX_BLOCK_TIME);
  }
示例#12
0
 public synchronized void addNumericData(
     final Set<MeasurementDataNumeric> dataSet, final FutureCallback<Void> callback) {
   if (numericQueue.remainingCapacity() > dataSet.size()) {
     for (final MeasurementDataNumeric data : dataSet) {
       try {
         if (data != null) {
           numericQueue.offer(data, 1, TimeUnit.SECONDS);
         }
       } catch (InterruptedException e) {
         // Modify the exception to include sane message telling us even the buffer is full..
         // and actually do something with it in MeasurementDataManagerBean ..
         callback.onFailure(
             new RuntimeException(
                 "The queue insert timed out after one second, can't finish the queue loading.",
                 e));
         return;
       }
     }
     callback.onSuccess(null);
   } else {
     callback.onFailure(new RuntimeException("The server is overloaded, queue is full."));
   }
 }
  @Test
  public void testConstructor() throws Exception {
    MockRegistrationReference mockRegistrationReference =
        new MockRegistrationReference(new MockIntraband());

    HttpClientSPIAgent httpClientSPIAgent =
        new HttpClientSPIAgent(_spiConfiguration, mockRegistrationReference);

    Assert.assertSame(mockRegistrationReference, httpClientSPIAgent.registrationReference);
    Assert.assertEquals(
        new InetSocketAddress(
            InetAddressUtil.getLoopbackInetAddress(), _spiConfiguration.getConnectorPort()),
        httpClientSPIAgent.socketAddress);

    BlockingQueue<Socket> socketBlockingQueue = httpClientSPIAgent.socketBlockingQueue;

    Assert.assertTrue(socketBlockingQueue.isEmpty());
    Assert.assertEquals(
        PropsValues.PORTAL_RESILIENCY_SPI_AGENT_CLIENT_POOL_MAX_SIZE,
        socketBlockingQueue.remainingCapacity());

    StringBundler sb = new StringBundler();

    sb.append("POST ");
    sb.append(HttpClientSPIAgent.SPI_AGENT_CONTEXT_PATH);
    sb.append(HttpClientSPIAgent.MAPPING_PATTERN);
    sb.append(" HTTP/1.1\r\nHost: localhost:");
    sb.append(_spiConfiguration.getConnectorPort());
    sb.append("\r\nContent-Length: 8\r\n\r\n");

    String httpServletRequestContentString = sb.toString();

    Assert.assertArrayEquals(
        httpServletRequestContentString.getBytes("US-ASCII"),
        httpClientSPIAgent.httpServletRequestContent);
  }
示例#14
0
 public static int getAvavilableConnections() {
   return maxPoolSize - clientPool.remainingCapacity();
 }
示例#15
0
 public int getQueueRemainingCapacity() {
   return queue.remainingCapacity();
 }
示例#16
0
 @Override
 public int remainingCapacity() {
   return delegate.remainingCapacity();
 }
 /**
  * Returns the number of additional elements that this queue can ideally (in the absence of memory
  * or resource constraints) accept without blocking.
  *
  * @return the remaining capacity
  */
 public synchronized int remainingCapacity() {
   return mQ.remainingCapacity();
 }
  @Override
  public int remainingCapacity() {

    return localInternalQueue.remainingCapacity();
  }