// create java thread pool. ExecutorService pool = Executors.newCachedThreadPool(); //initialize factory with backing pool PoolFiberFactory fiberFactory = new PoolFiberFactory(pool); Fiber fiber = fiberFactory.create(); fiber.start(); //use fiber for normal publishing and subscribing.
/** * Creates a new fiber in a suspended state. * * <p> * To start the returned fiber, call {@link Fiber#start(Tube,Packet,Fiber.CompletionCallback)}. * It will start executing the given {@link Tube} with the given {@link Packet}. * * @return new Fiber */ public Fiber createFiber() { return new Fiber(this); }
/** * Executes the fiber as much as possible. * */ private boolean doRun() { dumpFiberContext("running"); if (serializeExecution) { serializedExecutionLock.lock(); try { return _doRun(next); } finally { serializedExecutionLock.unlock(); } } else { return _doRun(next); } }
try { if (callback != null) { setCompletionCallback(callback); if(isTraceEnabled()) LOGGER.log(Level.FINE, "{0} resuming. Will have suspendedCount={1}", new Object[]{getName(), suspendedCount-1}); packet = resumePacket; if( --suspendedCount == 0 ) { if (!isInsideSuspendCallbacks) { List<Listener> listeners = getCurrentListeners(); for (Listener listener: listeners) { try { listener.fiberResumed(this); } catch (Throwable e) { if (isTraceEnabled()) LOGGER.log(Level.FINE, "Listener {0} threw exception: {1}", new Object[]{listener, e.getMessage()}); condition.signalAll(); } else if (forceSync || startedSync) { run(); } else { dumpFiberContext("resuming (async)"); owner.addRunnable(this); if (isTraceEnabled()) { LOGGER.log(Level.FINE, "{0} taking no action on resume because suspendedCount != 0: {1}", new Object[]{getName(), suspendedCount});
while(isReady(originalInterceptors)) { if (isCanceled) { next = null; last = popCont(); if (traceEnabled) LOGGER.log(Level.FINER, "{0} {1}.processException({2})", new Object[]{getName(), last, throwable}); na = last.processException(throwable); } else { if(next!=null) { if(traceEnabled) LOGGER.log(Level.FINER, "{0} {1}.processRequest({2})", new Object[]{getName(), next, packet != null ? "Packet@"+Integer.toHexString(packet.hashCode()) : "null"}); na = next.processRequest(packet); last = next; last = popCont(); if(traceEnabled) LOGGER.log(Level.FINER, "{0} {1}.processResponse({2})", new Object[]{getName(), last, packet != null ? "Packet@"+Integer.toHexString(packet.hashCode()) : "null"}); na = last.processResponse(packet); LOGGER.log(Level.FINER, "{0} {1} returned with {2}", new Object[]{getName(), last, na}); case NextAction.INVOKE: case NextAction.INVOKE_ASYNC: pushCont(last); case NextAction.ABORT_RESPONSE: abortResponse = true; if (isTraceEnabled()) {
Fiber currentFiber = Fiber.getCurrentIfSet(); if (currentFiber != null) { currentFiber.getCompletionCallback(); currentFiber.setCompletionCallback(null); ((BindingImpl) binding).createCodec(), null, null)); Fiber fiber = endpoint.getEngine().createFiber(); fiber.start(transport, packet, fiberCallback);
fiber.setDeliverThrowableInPacket(true); if (interceptor != null) { fiber.addInterceptor(interceptor); fiber.start(tube, request, cbak, binding.isFeatureEnabled(SyncStartForAsyncFeature.class) || !schedule);
private void completionCheck() { lock.lock(); try { // Don't trigger completion and callbacks if fiber is suspended if(!isCanceled && contsSize==0 && suspendedCount == 0) { if(isTraceEnabled()) LOGGER.log(Level.FINE, "{0} completed", getName()); clearListeners(); condition.signalAll(); if (completionCallback != null) { if (throwable != null) { if (isDeliverThrowableInPacket) { packet.addSatellite(new ThrowableContainerPropertySet(throwable)); completionCallback.onCompletion(packet); } else completionCallback.onCompletion(throwable); } else completionCallback.onCompletion(packet); } } } finally { lock.unlock(); } }
/** * DO NOT CALL THIS METHOD. This is an implementation detail * of {@link Fiber}. */ @Deprecated @Override public void run() { Container old = ContainerResolver.getDefault().enterContainer(owner.getContainer()); try { assert !synchronous; // doRun returns true to indicate an early exit from fiber processing if (!doRun()) { if (startedSync && suspendedCount == 0 && (next != null || contsSize > 0)) { // We bailed out of running this fiber we started as sync, and now // want to finish running it async startedSync = false; // Start back up as an async fiber dumpFiberContext("restarting (async) after startSync"); owner.addRunnable(this); } else { completionCheck(); } } } finally { ContainerResolver.getDefault().exitContainer(old); } }
@Override public NextAction processException(Throwable t) { try { return doThrow(t); } finally { Packet packet = Fiber.current().getPacket(); MessageUpdatableContext context = getContext(packet); initiateClosing(context.getMessageContext()); /* TODO revisit: commented this out as the modified packet is no longer used In future if the message is propagated even when an exception occurs, then uncomment context.updatePacket(); */ //Update Packet with user modifications //context.updatePacket(); } }
/** * (ADVANCED) Returns true if the current fiber is being executed synchronously. * <p/> * <p/> * Fiber may run synchronously for various reasons. Perhaps this is * on client side and application has invoked a synchronous method call. * Perhaps this is on server side and we have deployed on a synchronous * transport (like servlet.) * <p/> * <p/> * When a fiber is run synchronously (IOW by {@link #runSync(Tube, Packet)}), * further invocations to {@link #runSync(Tube, Packet)} can be done * without degrading the performance. * <p/> * <p/> * So this value can be used as a further optimization hint for * advanced {@link Tube}s to choose the best strategy to invoke * the next {@link Tube}. For example, a tube may want to install * a {@link FiberContextSwitchInterceptor} if running async, yet * it might find it faster to do {@link #runSync(Tube, Packet)} * if it's already running synchronously. */ public static boolean isSynchronous() { return current().synchronous; }
fiber.addInterceptor(fcsif.create()); fiber.start(tube, request, fiberCallback, getBinding().isFeatureEnabled(SyncStartForAsyncFeature.class) && !requestContext.containsKey(PREVENT_SYNC_START_FOR_ASYNC_INVOKE));
dumpFiberContext("starting (sync)"); run(); } else { this.started = true; dumpFiberContext("starting (async)"); owner.addRunnable(this);
this.packet = request; next = tubeline; doRun(); if (throwable != null) { if (isDeliverThrowableInPacket) { completionCheck();
if (isTraceEnabled()) { LOGGER.log(Level.FINE, "Thread entering _doRun(): {0}", currentThread); if (__doRun(isRequireUnlock, null /*ints*/)) { return true; if (isTraceEnabled()) { LOGGER.log(Level.FINE, "Thread leaving _doRun(): {0}", thread);
@Test public void simpleRequestResponse() throws InterruptedException { Fiber req = new ThreadFiber(); Fiber reply = new ThreadFiber(); req.start(); reply.start(); RequestChannel<String, Integer> channel = new MemoryRequestChannel<String, Integer>(); Callback<Request<String, Integer>> onReq = new Callback<Request<String, Integer>>() { public void onMessage(Request<String, Integer> message) { assertEquals("hello", message.getRequest()); message.reply(1); } }; channel.subscribe(reply, onReq); final CountDownLatch done = new CountDownLatch(1); Callback<Integer> onReply = new Callback<Integer>() { public void onMessage(Integer message) { assertEquals(1, message.intValue()); done.countDown(); } }; AsyncRequest.withOneReply(req, channel, "hello", onReply); assertTrue(done.await(10, TimeUnit.SECONDS)); req.dispose(); reply.dispose(); }
while(isReady(originalInterceptors)) { if (isCanceled) { next = null; last = popCont(); if (traceEnabled) LOGGER.log(Level.FINER, "{0} {1}.processException({2})", new Object[]{getName(), last, throwable}); na = last.processException(throwable); } else { if(next!=null) { if(traceEnabled) LOGGER.log(Level.FINER, "{0} {1}.processRequest({2})", new Object[]{getName(), next, packet != null ? "Packet@"+Integer.toHexString(packet.hashCode()) : "null"}); na = next.processRequest(packet); last = next; last = popCont(); if(traceEnabled) LOGGER.log(Level.FINER, "{0} {1}.processResponse({2})", new Object[]{getName(), last, packet != null ? "Packet@"+Integer.toHexString(packet.hashCode()) : "null"}); na = last.processResponse(packet); LOGGER.log(Level.FINER, "{0} {1} returned with {2}", new Object[]{getName(), last, na}); case NextAction.INVOKE: case NextAction.INVOKE_ASYNC: pushCont(last); case NextAction.ABORT_RESPONSE: abortResponse = true; if (isTraceEnabled()) {
try { if (callback != null) { setCompletionCallback(callback); if(isTraceEnabled()) LOGGER.log(Level.FINE, "{0} resuming. Will have suspendedCount={1}", new Object[]{getName(), suspendedCount-1}); packet = resumePacket; if( --suspendedCount == 0 ) { if (!isInsideSuspendCallbacks) { List<Listener> listeners = getCurrentListeners(); for (Listener listener: listeners) { try { listener.fiberResumed(this); } catch (Throwable e) { if (isTraceEnabled()) LOGGER.log(Level.FINE, "Listener {0} threw exception: {1}", new Object[]{listener, e.getMessage()}); condition.signalAll(); } else if (forceSync || startedSync) { run(); } else { dumpFiberContext("resuming (async)"); owner.addRunnable(this); if (isTraceEnabled()) { LOGGER.log(Level.FINE, "{0} taking no action on resume because suspendedCount != 0: {1}", new Object[]{getName(), suspendedCount});
Fiber currentFiber = Fiber.getCurrentIfSet(); if (currentFiber != null) { currentFiber.getCompletionCallback(); currentFiber.setCompletionCallback(null); ((BindingImpl) binding).createCodec(), null, null)); Fiber fiber = endpoint.getEngine().createFiber(); fiber.start(transport, packet, fiberCallback);