Commit Graph

50 Commits

Author SHA1 Message Date
Norman Maurer
c9aaa93d83
Allow to specify a EventLoopTaskQueueFactory for various EventLoopGroup implementations (#9247)
Motivation:

Sometimes it is desirable to be able to use a different Queue implementation for the EventLoop of a Channel. This is currently not possible without resort to reflection.

Modifications:

- Add a new constructor to Nio|Epoll|KQueueEventLoopGroup which allows to specify a factory which is used to create the task queue. This was the user can override the default implementation.
- Add test

Result:

Be able to change Queue that is used for the EventLoop.
2019-06-21 09:05:19 +02:00
Vladimir Kostyukov
0a0da67f43 Introduce SingleThreadEventLoop.registeredChannels (#8428)
Motivation:

Systems depending on Netty may benefit (telemetry, alternative even loop scheduling algorithms) from knowing the number of channels assigned to each EventLoop.

Modification:

Expose the number of channels registered in the EventLoop via SingleThreadEventLoop.registeredChannels.

Result:

Fixes #8276.
2019-03-28 11:33:12 +00:00
Nitesh Kant
77770374fb Ability to run a task at the end of an eventloop iteration.
Motivation:

This change is part of the change done in PR #5395 to provide an `AUTO_FLUSH` capability.
Splitting this change will enable to try other ways of implementing `AUTO_FLUSH`.

Modifications:



Two methods:

```java
void executeAfterEventLoopIteration(Runnable task);


boolean removeAfterEventLoopIterationTask(Runnable task);
```
are added to `SingleThreadEventLoop` class for adding/removing a task to be executed at the end of current/next iteration of this `eventloop`.

In order to support the above, a few methods are added to `SingleThreadEventExecutor`

```java
protected void afterRunningAllTasks() { }
```

This is invoked after all tasks are run for this executor OR if the passed timeout value for `runAllTasks(long timeoutNanos)` is expired.

Added a queue of `tailTasks` to `SingleThreadEventLoop` to hold all tasks to be executed at the end of every iteration.


Result:



`SingleThreadEventLoop` now has the ability to execute tasks at the end of an eventloop iteration.
2016-07-12 10:22:15 +02:00
Norman Maurer
731f52fdf7 Allow to inject RejectedExecutionHandler for different EventLoops and EventExecutors
Motiviation:

Sometimes it is useful to allow to specify a custom strategy to handle rejected tasks. For example if someone tries to add tasks from outside the eventloop it may make sense to try to backoff and retries and so give the executor time to recover.

Modification:

Add RejectedEventExecutor interface and implementations and allow to inject it.

Result:

More flexible handling of executor overload.
2016-06-24 17:08:30 +02:00
Norman Maurer
a0d4fb16fc Allow to set max capacity for task queue for EventExecutors and EventLoops
Motivation:

To restrict the memory usage of a system it is sometimes needed to adjust the number of max pending tasks in the tasks queue.

Modifications:

- Add new constructors to modify the number of allowed pending tasks.
- Add system properties to configure the default values.

Result:

More flexible configuration.
2016-06-24 14:00:50 +02:00
Xiaoyan Lin
a5006c1969 Add a EventLoopGroup.register(ChannelPromise)
Motivation:

EventLoopGroup.register doesn't need the Channel paramter when ChannelPromise is provided as we can get the Channel from ChannelPromise. Resolves #2422.

Modifications:

- Add EventLoopGroup.register(ChannelPromise)
- Deprecate EventLoopGroup.register(Channel, ChannelPromise)

Result:

EventLoopGroup.register is more convenient as people only need to set one parameter.
2016-05-21 18:40:17 +02:00
Norman Maurer
68cd670eb9 Remove ChannelHandlerInvoker
Motivation:

We tried to provide the ability for the user to change the semantics of the threading-model by delegate the invoking of the ChannelHandler to the ChannelHandlerInvoker. Unfortunually this not really worked out quite well and resulted in just more complexity and splitting of code that belongs together. We should remove the ChannelHandlerInvoker again and just do the same as in 4.0

Modifications:

Remove ChannelHandlerInvoker again and replace its usage in Http2MultiplexCodec

Result:

Easier code and less bad abstractions.
2016-05-17 11:14:00 +02:00
Trustin Lee
844362a947 User-definable thread model via ChannelHandlerInvoker
Motivation:

While the default thread model provided by Netty is reasonable enough for most applications, some users might have a special requirement for the thread model.  Here are a few examples:

- A user might want to invoke handlers from the caller thread directly, assuming that his or her application is completely asynchronous and does not make any invocation from non-I/O thread.  In this case, the default invoker implementation will only add the overhead of checking if the current thread is an I/O thread or not.
- A user might want to invoke handlers from different threads depending on the type of events flexibly.

Modifications:

- Backport 132af3a485 which is a fix for #1912
  - Add a new interface called 'ChannelHandlerInvoker' that performs the invocation of event handler methods.
  - Add pipeline manipulation methods that accept ChannelHandlerInvoker
- The differences from the original commit:
  - Separated the irrelevant changes out
  - Channel.eventLoop is null until the registration is complete in this branch, so Channel.Unsafe.invoker() doesn't work before registration.
  - Deregistration is not gone in this branch, so the methods related with deregistration were added to ChannelHandlerInvoker
2014-03-24 18:09:27 +09:00
Trustin Lee
007694b963 Implement EventExecutor.parent() in AbstractEventExecutor
Motivation:

EventExecutor.parent() and EventLoop.parent() almost always return a constant parent executor.  There's not much reason to let it implemented in subclasses.

Modifications:

- Implement AbstractEventExecutor.parent() with an additional contructor
- Add AbstractEventLoop so that subclasses extend AbstractEventLoop, which implements parent() appropriately
- Remove redundant parent() implementations in the subclasses
- Fix inspector warnings

Result:

Less duplication.
2014-03-24 11:05:51 +09:00
Vladimir Krivosheev
eb308cfff6 ability to use Executor instead of ThreadFactory 2014-02-13 16:14:41 -08:00
Norman Maurer
64c3f58279 Not wakeup the EventLoop for writes as they will not cause a flush anyway 2014-02-01 13:45:27 +01:00
Trustin Lee
89a7cb8e71 More graceful registration failure
- Fixes #2060
- Ensure to return a future/promise implementation that does not fail with 'not registered to an event loop' error for registration operations
- If there is no usable event loop available, GlobalEventExecutor.INSTANCE is used as a fallback.
2013-12-21 18:08:58 +09:00
Norman Maurer
a07abee55f Add and correct javadocs 2013-07-13 19:42:02 +02:00
Trustin Lee
23d0178494 Introduce EventExecutor.shutdownGracefully() that deprecates shutdown()
shutdownGracefully() provides two optional parameters that give more
control over when an executor has to be shut down.

- Related issue: #1307
- Add shutdownGracefully(..) and isShuttingDown()
- Deprecate shutdown() / shutdownNow()
- Replace lastAccessTime with lastExecutionTime and update it after task
  execution for accurate quiet period check
  - runAllTasks() and runShutdownTasks() update it automatically.
  - Add updateLastExecutionTime() so that subclasses can update it
- Add a constructor parameter that tells not to add an unncessary wakeup
  task in execute() if addTask() wakes up the executor thread
  automatically.  Previously, execute() always called wakeup() after
  addTask(), which often caused an extra dummy task in the task queue.
- Use shutdownGracefully() wherever possible / Deprecation javadoc
- Reduce the running time of SingleThreadEventLoopTest from 40s to 15s
  using custom graceful shutdown parameters

- Other changes made along with this commit:
  - takeTask() does not throw InterruptedException anymore.
    - Returns null on interruption or wakeup
  - Make sure runShutdownTasks() return true even if an exception was
    raised while running the shutdown tasks
  - Remove unnecessary isShutdown() checks
  - Consistent use of SingleThreadEventExecutor.nanoTime()

Replace isWakeupOverridden with a constructor parameter
2013-05-01 10:52:38 +09:00
Trustin Lee
4097dee49d Make SingleThreadEventExecutor independent from TaskScheduler
- Related issue: #817
2013-03-22 09:00:38 +09:00
Trustin Lee
a980638190 Ensure the best effort is made even if future listeners could not be notified / Handle registration failure in a robust manner
- Related: #1187
2013-03-21 17:48:10 +09:00
Norman Maurer
88cc8c1739 [#1065] Provide Future/Promise without channel reference 2013-03-07 07:21:37 +01:00
Trustin Lee
24acfe7008 Remove io.netty.monitor as discussed in #922 2013-01-18 11:08:57 +09:00
Trustin Lee
eb337ff5a7 Fix various inspection warnings 2013-01-10 15:23:58 +09:00
Courtney Robinson
3a52cc410a Add some of the metrics mentioned in #718
use single static initialization of available metrics monitor registries

* This changes the original implementation to work in a similar way to
how slf4j selects and loads an implementation.
* Uses a single static instance so intialization is done only once.
* Doesn't throw IllegalStateException if multiple implementations are
found on the classpath. It instead selects and uses the first
implementation returned by iterator()
* Class left as an iterable to keep the API the same

add yammer metrics to examples to allow them to publish metrics

publish the number of threads used in an EventLoopGroup see issue #718

* seems like the better place to put this because it sets the default
thread count if the MultithreadEventLoopGroup uses super(0,...)
* It also happens to be the common parent class amongst all the
MultiThreadedEventLoopGroup implementations
* Count is reported for
io.netty.channel.{*,.local,.socket.aio,.socket.nio}

fix cosmetic issues pointed out in pull request and updated notice.txt

see https://github.com/netty/netty/pull/780

count # of channels registered in single threaded event loop

measure how many times Selector.select return before SELECT_TIME
2013-01-04 11:27:49 +01:00
Norman Maurer
4e77bacdf7 [#873] [#868] Split ChannelFuture into ChannelFuture and ChannelPromise 2012-12-31 23:27:16 +09:00
Norman Maurer
b7b17209ea Next round of javadocs cleanup and fixes. Also limit the visibility of FailedChannelFuture 2012-12-18 07:23:42 +01:00
Trustin Lee
dbbc6ad73f Reduce the chance of RejectedExecutionException
When a Netty application shuts down, a user often sees a REE
(RejectedExecutionException).

A REE is raised due to various reasons we don't have control over, such
as:

- A client connects to a server while the server is shutting down.

- An event is triggered for a closed Channel while its event loop is
  also shutting down.  Some of them are:
  - channelDeregistered (triggered after a channel is closed)
  - freeIn/OutboundBuffer (triggered after channelDeregistered)
  - userEventTriggered (triggered anytime)

To address this issue, a new method called confirmShutdown() has been
added to SingleThreadEventExecutor.  After a user calls shutdown(),
confirmShutdown() runs any remaining tasks in the task queue and ensures
no events are triggered for last 2 seconds.  If any task are added to
the task queue before 2 seconds passes, confirmShutdown() prevents the
event loop from terminating by returning false.

Now that SingleThreadEventExecutor needs to accept tasks even after
shutdown(), its execute() method only rejects the task after the event
loop is terminated (i.e. isTerminated() returns true.)  Except that,
there's no change in semantics.

SingleThreadEventExecutor also checks if its subclass called
confirmShutdown() in its run() implementation, so that Netty developers
can make sure they shut down their event loop impementation correctly.

It also fixes a bug in AioSocketChannel, revealed by delayed shutdown,
where an inboundBufferUpdated() event is triggered on a closed Channel
with deallocated buffers.

Caveats:

Because SingleThreadEventExecutor.takeTask() does not have a notion of
timeout, confirmShutdown() adds a dummy task (WAKEUP_TASK) to wake up
takeTask() immediately and instead sleeps hard-coded 100ms.  I'll
address this issue later by modifying takeTask() times out dynamically.

Miscellaneous changes:

SingleThreadEventExecutor.wakeup() now has the default implementation.
Instead of interrupting the current thread, it simply adds a dummy task
(WAKEUP_TASK) to the task queue, which is more elegant and efficient.
NioEventLoop is the only implementation that overrides it. All other
implementations' wakeup()s were removed thanks to this change.
2012-11-22 20:36:13 +01:00
Trustin Lee
8bfbebc772 Rename TaskScheduler to ChannelTaskScheduler 2012-08-19 15:10:09 +09:00
Trustin Lee
421eabe666 [#473] Fix elevated context switching in SingleThreadEventExecutor
- Remove polling in SingleThreadEventExecutor
- Create a dedicated scheduled task scheduler called 'TaskScheduler'
- TaskScheduler is created per EventLoopGroup / EventExecutorGroup
- SingleThreadEventExecutor delegates all scheduled execution requests
  to TaskScheduler provided as a constructor parameter
- TaskScheduler is a specialized form of single threaded 
  ScheduledExecutorService which requires an EventExecutor as a
  parameter for all requests.
2012-08-18 18:40:21 +09:00
Trustin Lee
d298707198 [#502] Split EventLoop/EventExecutor into parent and children
- Add EventExecutorGroup and EventLoopGroup
- EventExecutor and EventLoop extends EventExecutorGroup and
  EventLoopGroup
  - They form their own group so that .next() returns itself.
- Rename Bootstrap.eventLoop() to group()
- Rename parameter names such as executor to group
- Rename *EventLoop/Executor to *EventLoop/ExecutorGroup
- Rename *ChildEventLoop/Executor to *EventLoop/Executor
2012-08-10 20:17:18 +09:00
Trustin Lee
42380b54b3 Revert file mode 2012-07-07 14:39:35 +09:00
Norman Maurer
f8ef5d5d78 Next round for async channel api support a.k.a nio2. See See #396 2012-06-14 21:02:47 +02:00
Trustin Lee
1eced1e9e3 Update license headers 2012-06-04 13:31:44 -07:00
Trustin Lee
04cf1c8199 Use custom thread factory by default to better recognize the threads
... from their names
2012-06-01 22:57:54 -07:00
Trustin Lee
61e169e53a Remove EventExecutor.parent(), which is of no use 2012-06-01 22:33:53 -07:00
Trustin Lee
141a05c831 Strict thread model / Allow assign an executor to a handler
- Add EventExecutor and make EventLoop extend it
- Add SingleThreadEventExecutor and MultithreadEventExecutor
- Add EventExecutor's default implementation
- Fixed an API design problem where there is no way to get non-bypass
  buffer of desired type
2012-06-01 17:51:19 -07:00
Trustin Lee
42abb6df3a QueueFactory cleanup
- Really attempt to create a queue to determine LTQ can be initialized
  in runtime, and cache the result
- Remove unnecessary Class<T> parameter in createQueue()
- Remove unused createQueue(Collection)
2012-05-30 16:19:22 -07:00
Trustin Lee
47fa2ef2e8 Use LinkedHashSet instead of HashSet to preserve order of execution 2012-05-30 10:17:45 -07:00
Trustin Lee
c17e5b458a Typo 2012-05-30 04:28:01 -07:00
Trustin Lee
4154f42520 Less restriction in shutdown hook modification 2012-05-30 04:27:19 -07:00
Trustin Lee
078a502c5f Add shutdown hooks to SingleThreadEventLoop
- LocalChannel and LocalServerChannel uses it to close themselves on
  shutdown
- LocalEcho example does not call close() anymore because the channels
  are closed automatically on shutdown
2012-05-30 04:23:15 -07:00
Trustin Lee
e48281471b Limit future notification stack depth / Robost writeCounter management
- Also ported the discard example while testing this commit
2012-05-28 05:05:49 -07:00
Trustin Lee
7327bb3522 Add SingleThreadEventLoop.runAllTasks()
- Removed duplicated processTaskQueue() in child event loops
- Simplified the cleanup of cancelled keys in NIO transport
2012-05-27 04:43:48 -07:00
Trustin Lee
e2d69120bb Ported OIO socket/datagram transport to the new API 2012-05-25 13:58:56 -07:00
Trustin Lee
59f11ed64f Optimize AbstractChannel and related classes
- AbstractChannel.doRead() is split into two versions so that the
  implementation doesn't have to validate the buffer type.
- Optimized ChannelBufferHolder a little bit
- Reduced GC related with flush future notification
  - Added FlushCheckpoint and DefaultChannelFuture implements it
    opportunistically
-
2012-05-25 06:16:25 -07:00
Trustin Lee
25599018f2 Tiny bit of optimization in event loop 2012-05-24 21:04:12 -07:00
Trustin Lee
83026f29a4 Make EventLoop a ScheduledExecutorService
- SingleThreadEventLoop now implements ScheduledExecutorService
  - Scheduled tasks are automatically fetched into taskQueue by
    pollTask() and takeTask()
- Removed MapBackedSet because Java 6 provides it
2012-05-11 20:19:57 +09:00
Trustin Lee
cb718a07c8 Move ChannelFutureFactory.newVoidFuture() to Channel.Unsafe() / Cleanup 2012-05-11 00:57:42 +09:00
Trustin Lee
129a2af86a Initial working version of the echo server example
- Optimized AbstractChannelBuffer.discardReadBytes()
- Split ChannelHandlerInvoker into ChannelInboundInvoker and
  ChannelOutboundInvoker
  - Channel implements ChannelOutboundInvoker
  - ChannelOutboundInvoker.nextOut() is now out()
  - ChannelOutboundHandlerContext.out() is now prevOut()
  - Added the outbound operations without future
    parameter to ChannelOutboundInvoker for user convenience
- All async operations which requires a ChannelFuture as a parameter
  now returns ChannelFuture for user convenience
- Added ChannelFutureFactory.newVoidFuture() to allow a user specify
  a dummy future that is of no use
  - I'm unsure if it is actually a good idea to introduce it. It might
    go away later.
- Made the contract of AbstractChannel.doXXX() much simpler and moved
  all common code up to AbstractChannel.DefaultUnsafe
- Added Channel.isOpen()
- Fixed a bug where MultithreadEventLoop always shut down its child
  event loops on construction
- Maybe more changes I don't remember :-)
2012-05-09 22:09:06 +09:00
Trustin Lee
9e6f8b46df Retrofit the NIO transport with the new API / improve the new API
- Remove the classes and properties that are not necessary anymore
- Remove SingleThreadEventLoop.newRegistrationTask() and let
  Channel.Unsafe handle registration by itself
- Channel.Unsafe.localAddress() and remoteAddress()
  - JdkChannel is replaced by Channel.Unsafe.
2012-05-02 15:01:58 +09:00
Trustin Lee
470e7da5d7 Add MultithreadEventLoop
- Add EventLoopException to wrap the exceptions while an event loop does
something
- Make EventLoop.register() return EventLoop so that the caller knows
the actual EventLoop that will handle the Channel even if the caller
called register() from MultithreadEventLoop
2012-04-29 18:40:55 +09:00
Trustin Lee
e76e2aeac8 Add missing @Override annotation 2012-04-29 17:59:42 +09:00
Trustin Lee
0d8afa7a4c attach -> register 2012-04-03 22:19:35 +09:00
Trustin Lee
116054a364 Initial incomplete checkin of the event loop API 2012-04-03 22:03:04 +09:00