本文整理汇总了Java中java.util.concurrent.BlockingQueue.offer方法的典型用法代码示例。如果您正苦于以下问题:Java BlockingQueue.offer方法的具体用法?Java BlockingQueue.offer怎么用?Java BlockingQueue.offer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.BlockingQueue
的用法示例。
在下文中一共展示了BlockingQueue.offer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: rejectedExecution
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
public void rejectedExecution(Runnable task, ThreadPoolExecutor executor)
{
((DebuggableThreadPoolExecutor) executor).onInitialRejection(task);
BlockingQueue<Runnable> queue = executor.getQueue();
while (true)
{
if (executor.isShutdown())
{
((DebuggableThreadPoolExecutor) executor).onFinalRejection(task);
throw new RejectedExecutionException("ThreadPoolExecutor has shut down");
}
try
{
if (queue.offer(task, 1000, TimeUnit.MILLISECONDS))
{
((DebuggableThreadPoolExecutor) executor).onFinalAccept(task);
break;
}
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
}
}
示例2: terminateSession
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* The implementation for terminateSession() function.
* It removes the session to queue association.
* @param sessionid
* @throws TException
*/
@Override
public void terminateSession(String sessionid)
throws org.apache.thrift.TException {
if (!msgQueues.containsKey(sessionid)) {
return;
}
SessionQueue pQueue = msgQueues.get(sessionid);
log.debug("terminateSession: SessionId: " + sessionid + "\n");
String data = "FilterTimeout";
ByteBuffer bb = ByteBuffer.wrap(data.getBytes());
BlockingQueue<ByteBuffer> queue = pQueue.getQueue();
if (queue != null) {
if (!queue.offer(bb)) {
log.error("Failed to queue message for session: " + sessionid);
}
msgQueues.remove(sessionid);
} else {
log.error("queue for session {} is null", sessionid);
}
}
示例3: closeConnections
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* Close connections that are idle or optionally close all connections.
* Connections are considered "idle" if they have not been used in 10 seconds.
*
* @param closeNonIdleConnections if <code>true</code> will close all connection; if <code>false</code> will close only idle connections
*/
private void closeConnections(final boolean closeNonIdleConnections) {
for (final Map.Entry<Tuple<String, Integer>, BlockingQueue<FileTransferIdleWrapper>> entry : fileTransferMap.entrySet()) {
final BlockingQueue<FileTransferIdleWrapper> wrapperQueue = entry.getValue();
final List<FileTransferIdleWrapper> putBack = new ArrayList<>();
FileTransferIdleWrapper wrapper;
while ((wrapper = wrapperQueue.poll()) != null) {
final long lastUsed = wrapper.getLastUsed();
final long nanosSinceLastUse = System.nanoTime() - lastUsed;
if (!closeNonIdleConnections && TimeUnit.NANOSECONDS.toMillis(nanosSinceLastUse) < IDLE_CONNECTION_MILLIS) {
putBack.add(wrapper);
} else {
try {
wrapper.getFileTransfer().close();
} catch (final IOException ioe) {
getLogger().warn("Failed to close Idle Connection due to {}", new Object[] {ioe}, ioe);
}
}
}
for (final FileTransferIdleWrapper toPutBack : putBack) {
wrapperQueue.offer(toPutBack);
}
}
}
示例4: main
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(1);
queue.add("add");
//
String peek = queue.peek();
System.out.println(peek);
queue.poll();
boolean offer = queue.offer("offer");
if (!offer) {
System.out.println("it is't possible to do so immediately");
}
System.out.println(queue.take());
queue.put("put operation");
System.out.println(queue.take());
}
示例5: singleThreadExecutor
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* Returns a single threaded executor which uses one invocation
* of the parent executor to execute tasks (in sequence).
*
* Use a null valued Runnable to terminate.
*/
// TODO: this is a blocking way of doing this;
public static Executor singleThreadExecutor(Executor parent) {
BlockingQueue<Optional<Runnable>> queue = new LinkedBlockingQueue<>();
parent.execute(() -> {
while (true) {
try {
Optional<Runnable> o = queue.take();
if (!o.isPresent()) {
return;
}
o.get().run();
} catch (InterruptedException ex) {
return;
}
}
});
return new Executor() {
@Override
public void execute(Runnable command) {
queue.offer(Optional.ofNullable(command));
}
};
}
示例6: rejectedExecution
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) {
if (threadName != null) {
LOG.error("txTransaction Thread pool [{}] is exhausted, executor={}", threadName, executor.toString());
}
if (!executor.isShutdown()) {
BlockingQueue<Runnable> queue = executor.getQueue();
int discardSize = queue.size() >> 1;
for (int i = 0; i < discardSize; i++) {
queue.poll();
}
queue.offer(runnable);
}
}
示例7: put
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* Put and offer follow the same pattern:
* 1. Get a priorityLevel from the scheduler
* 2. Get the nth sub-queue matching this priorityLevel
* 3. delegate the call to this sub-queue.
*
* But differ in how they handle overflow:
* - Put will move on to the next queue until it lands on the last queue
* - Offer does not attempt other queues on overflow
*/
@Override
public void put(E e) throws InterruptedException {
int priorityLevel = scheduler.getPriorityLevel(e);
final int numLevels = this.queues.size();
while (true) {
BlockingQueue<E> q = this.queues.get(priorityLevel);
boolean res = q.offer(e);
if (!res) {
// Update stats
this.overflowedCalls.get(priorityLevel).getAndIncrement();
// If we failed to insert, try again on the next level
priorityLevel++;
if (priorityLevel == numLevels) {
// That was the last one, we will block on put in the last queue
// Delete this line to drop the call
this.queues.get(priorityLevel-1).put(e);
break;
}
} else {
break;
}
}
signalNotEmpty();
}
示例8: offer
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
@Override
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
int priorityLevel = scheduler.getPriorityLevel(e);
BlockingQueue<E> q = this.queues.get(priorityLevel);
boolean ret = q.offer(e, timeout, unit);
signalNotEmpty();
return ret;
}
示例9: pushMessageSync
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* The implementation for pushMessageSync() function.
*
* @param msg
* @return 1 for success, 0 for failure
* @throws TException
*/
@Override
public int pushMessageSync(Message msg)
throws org.apache.thrift.TException {
if (msg == null) {
log.error("Could not push empty message");
return 0;
}
List<String> sessionids = msg.getSessionIDs();
for (String sid : sessionids) {
SessionQueue pQueue = null;
if (!msgQueues.containsKey(sid)) {
pQueue = new SessionQueue();
msgQueues.put(sid, pQueue);
} else {
pQueue = msgQueues.get(sid);
}
log.debug("pushMessageSync: SessionId: " + sid +
" Receive a message, " + msg.toString() + "\n");
ByteBuffer bb = ByteBuffer.wrap(msg.getPacket().getData());
//ByteBuffer dst = ByteBuffer.wrap(msg.getPacket().toString().getBytes());
BlockingQueue<ByteBuffer> queue = pQueue.getQueue();
if (queue != null) {
if (!queue.offer(bb)) {
log.error("Failed to queue message for session: " + sid);
} else {
log.debug("insert a message to session: " + sid);
}
} else {
log.error("queue for session {} is null", sid);
}
}
return 1;
}
示例10: getResult
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* 获取结果
* @param blockingQueue
* @param timeout
* @param unit
* @return
* @throws InterruptedIOException
*/
public static Object getResult(BlockingQueue<Object> blockingQueue,long timeout, TimeUnit unit) throws InterruptedIOException {
Object result;
try {
result = blockingQueue.poll(timeout, unit);
if (result == null) {
if (!blockingQueue.offer("")) {
result = blockingQueue.take();
}
}
} catch (InterruptedException e) {
throw ExceptionUtil.initCause(new InterruptedIOException(e.getMessage()), e);
}
return result;
}
示例11: enqueue
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
protected void enqueue(BlockingQueue<T> outputQueue, T segment) throws InterruptedException {
boolean enqueued = false;
while(!enqueued) {
enqueued = outputQueue.offer(segment, 500, TimeUnit.MILLISECONDS);
}
}
示例12: rejectedExecution
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) {
if (threadName != null) {
LOG.error("MythTransaction Thread pool [{}] is exhausted, executor={}", threadName, executor.toString());
}
if (!executor.isShutdown()) {
BlockingQueue<Runnable> queue = executor.getQueue();
int discardSize = queue.size() >> 1;
for (int i = 0; i < discardSize; i++) {
queue.poll();
}
queue.offer(runnable);
}
}
示例13: forceAdd
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
private static <T> void forceAdd(BlockingQueue<T> queue, T value) {
while (!queue.offer(value)) {
LOG.warning("Failed to add to queue, trying again...");
}
}
示例14: deserialize
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* @param stream InputStream containing JSON data
* @param segmentsQueue Queue retrieving parsed way segment objects
* @param metadataQueue Queue retrieving parsed metadata object; there will be retrieved only one object
*/
@Override
public void deserialize(InputStream stream, BlockingQueue<T> segmentsQueue,
BlockingQueue<IWayGraphVersionMetadata> metadataQueue)
throws WaySegmentDeserializationException {
try {
JsonParser jp = jsonFactory.createParser(stream);
JsonToken token = jp.nextToken();
long count = 0;
ISegmentAdapter<IBaseSegmentDTO, T> adapter = null;
while (!jp.isClosed()){
token = jp.nextToken();
if (token != null && token != JsonToken.END_ARRAY) {
if (jp.getCurrentToken() == JsonToken.FIELD_NAME &&
jp.getCurrentName().equals("graphVersionMetadata")) {
jp.nextToken();
IGraphVersionMetadataDTO dto = jp.readValueAs(GraphVersionMetadataDTOImpl.class);
IWayGraphVersionMetadata metadata = metadataAdapter.adapt(dto);
metadataQueue.offer(metadata, 500, TimeUnit.MILLISECONDS);
}
// extract type of segments. its encoded as the name of the array field holding the segments
else if (jp.getCurrentToken() == JsonToken.FIELD_NAME) {
String segmentType = jp.getCurrentName();
adapter = this.getAndRegisterDeserializers(segmentType);
}
else if (jp.getCurrentToken() != JsonToken.END_OBJECT) {
enqueue(segmentsQueue, processSegment(jp, adapter));
count++;
}
}
}
log.info("parsed and enqueued: " + count + " segments");
} catch (Exception e) {
throw new WaySegmentDeserializationException(e.getMessage(),e);
}
}
示例15: pushMessageSync
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* The implementation for pushMessageSync() function.
*
* @param msg
* @return 1 for success, 0 for failure
* @throws TException
*/
@Override
@LogMessageDocs({
@LogMessageDoc(level="ERROR",
message="Could not push empty message",
explanation="An empty message was sent to the packet streamer",
recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
@LogMessageDoc(level="ERROR",
message="queue for session {sessionId} is null",
explanation="The queue for the packet streamer session " +
"is missing",
recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG)
})
public int pushMessageSync(Message msg)
throws org.apache.thrift.TException {
if (msg == null) {
log.error("Could not push empty message");
return 0;
}
List<String> sessionids = msg.getSessionIDs();
for (String sid : sessionids) {
SessionQueue pQueue = null;
if (!msgQueues.containsKey(sid)) {
pQueue = new SessionQueue();
msgQueues.put(sid, pQueue);
} else {
pQueue = msgQueues.get(sid);
}
log.debug("pushMessageSync: SessionId: " + sid +
" Receive a message, " + msg.toString() + "\n");
ByteBuffer bb = ByteBuffer.wrap(msg.getPacket().getData());
//ByteBuffer dst = ByteBuffer.wrap(msg.getPacket().toString().getBytes());
BlockingQueue<ByteBuffer> queue = pQueue.getQueue();
if (queue != null) {
if (!queue.offer(bb)) {
log.error("Failed to queue message for session: " + sid);
} else {
log.debug("insert a message to session: " + sid);
}
} else {
log.error("queue for session {} is null", sid);
}
}
return 1;
}