Commit Graph

63 Commits

Author SHA1 Message Date
Scott Mitchell
a043cf4a98 Catch exceptions from PlatformDependent#getSystemClassLoader
Motivation:
PlatformDependent#getSystemClassLoader may throw a wide variety of exceptions based upon the environment. We should handle all exceptions and continue initializing the slow path if an exception occurs.

Modifications:
- Catch Throwable in cases where PlatformDependent#getSystemClassLoader is used

Result:
Fixes https://github.com/netty/netty/issues/6038
2016-11-19 09:23:25 -08:00
Norman Maurer
a09e56850e [#5882] Ensure we even process tasks if processing of ready channels throws an Exception in event loop.
Motivation:

If an exception is thrown while processing the ready channels in the EventLoop we should still run all tasks as this may allow to recover. For example a OutOfMemoryError may be thrown and runAllTasks() will free up memory again. Beside this we should also ensure we always allow to shutdown even if an exception was thrown.

Modifications:

- Call runAllTasks() in a finally block
- Ensure shutdown is always handles.

Result:

More robust EventLoop implementations for NIO and Epoll.
2016-10-10 07:49:57 +02:00
Norman Maurer
3cf7ccbd3c Process OP_WRITE before OP_READ to free memory faster
Motivation:

We should better first process OP_WRITE before OP_READ as this may allow us to free memory in a faster fashion for previous queued writes.

Modifications:

Process OP_WRITE before OP_READ

Result:

Free memory faster for queued writes.
2016-10-10 07:42:39 +02:00
Norman Maurer
30fe2e868f Call finishConnect() before try to call read(...) / write(...) when using NIO
Motivation:

The JDK implementation of SocketChannel has an internal state that is tracked for its operations. Because of this we need to ensure we call finishConnect() before try to call read(...) / write(...) as otherwise it may produce a NotYetConnectedException.

Modifications:

First process OP_CONNECT flag.

Result:

No more possibility of NotYetConnectedException because OP_CONNECT is handled not early enough when processing interestedOps for a Channel.
2016-09-01 08:55:02 +02:00
Jason Tedor
00c0664ef8 Avoid inaccessible object exception replacing set
Motivation:

When attempting to set the selectedKeys fields on the selector
implementation, JDK 9 can throw an inaccessible object exception.

Modications:

Catch and log this exception as an possible course of action if the
sun.nio.ch package is not exported from java.base.

Result:

The selector replacement will fail gracefully as an expected course of
action if the sun.nio.ch package is not exported from java.base.
2016-08-31 13:59:48 +02:00
Jason Tedor
a6dfd08812 Mark initialization of selector as privileged
Motivation:

Instrumenting the NIO selector implementation requires special
permissions. Yet, the code for performing this instrumentation is
executed in a manner that would require all code leading up to the
initialization to have the requisite permissions. In a restrictive
environment (e.g., under a security policy that only grants the
requisite permissions the Netty transport jar but not to application
code triggering the Netty initialization), then instrumeting the
selector will not succeed even if the security policy would otherwise
permit it.

Modifications:

This commit marks the necessary blocks as privileged. This enables
access to the necessary resources for instrumenting the selector. The
idea is that we are saying the Netty code is trusted, and as long as the
Netty code has been granted the necessary permissions, then we will
allow the caller access to these resources even though the caller itself
might not have the requisite permissions.

Result:

The selector can be instrumented in a restrictive security environment.
2016-08-05 19:01:57 +02:00
Jason Tedor
32629078a2 Mark setting of sun.nio.ch.bugLevel as privileged
Motivation:

Writing to a system property requires permissions. Yet the code for
setting sun.nio.ch.bugLevel is not marked as privileged. In a
restrictive environment (e.g., under a security policy that only grants
the requisite permissions the Netty transport jar but not to application
code triggering the Netty initialization), writing to this system
property will not succeed even if the security policy would otherwise
permit it.

Modifications:

This commt marks the necessary code block as privileged. This enables
writing to this system property. The idea is that we are saying the
Netty code is trusted, and as long as the Netty code has been granted
the necessary permissions, then we will allow the caller access to these
resources even though the caller itself might not have the requisite
permissions.

Result:

The system property sun.nio.ch.bugLevel can be written to in a
restrictive security environment.
2016-08-05 18:58:34 +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
Norman Maurer
31e0ac1d22 Expose the SelectorProvider used by the NioEventLoop
Motivation:

If a user writes an own nio based transport which uses a special SelectorProvider it is useful to be able to get the SelectorProvider that is used by a NioEventLoop. This way this can be used when implement AbstractChannel.isCompatible(...) and check that the SelectorProvider is the correct one.

Modifications:

Expose the SelectorProvider.

Result:

Be able to get the SelectorProvider used by a NioEventLoop.
2016-06-21 14:05:44 +02:00
Norman Maurer
418550914a Log Selector instance when Selector needs to be rebuild
Motivation:

To better debug why a Selector need to be rebuild it is useful to also log the instance of the Selector.

Modifications:

Add logger instance to the log message.

Result:

More useful log message.
2016-06-17 06:19:23 +02:00
Norman Maurer
86f53083e7 [#5297] Ensure calling NioEventLoop.pendingTasks() and EpollEventLoop.pendingTasks() will not produce livelock
Motivation:

SingleThreadEventExecutor.pendingTasks() will call taskQueue.size() to get the number of pending tasks in the queue. This is not safe when using MpscLinkedQueue as size() is only allowed to be called by a single consumer.

Modifications:

Ensure size() is only called from the EventLoop.

Result:

No more livelock possible when call pendingTasks, no matter from which thread it is done.
2016-05-28 20:04:07 +02:00
Hyangtack Lee
f44f3e7926 NioEventLoop ensures that all submitted tasks are executed immediately.
Motivation:
If a task was submitted when wakenUp value was true, the task didn't get a chance to call Selector#wakeup.
So we need to check task queue again before executing select operation. If we don't, the task might be pended until select operation was timed out.
It might be pended until idle timeout if IdleStateHandler existed in pipeline.

Modifications:
Execute Selector#select in a non-blocking manner if there's a task submitted when wakenUp value was true.

Result:
Every tasks in NioEventLoop will not be pended.
2016-05-17 07:43:46 +02:00
Scott Mitchell
04e33fd2d8 NioEventLoop closes channel even if channel is not registered
Motivation:
If a channel is deregistered from an NioEventLoop the associated SelectionKey is cancelled. If the NioEventLoop has yet to process a pending event as a result of that SelectionKey then the NioEventLoop will see the SelecitonKey is invalid and close the channel. The NioEventLoop should not close a channel if it is not registered with that NioEventLoop.

Modifications:
- NioEventLoop.processSelectedKeys should check that the channel is still registered to itself before closing the channel

Result:
NioEventLoop doesn't close a channel that is no longer registered to it when the SelectionKey is invalid
Fixes https://github.com/netty/netty/issues/5125
2016-04-21 09:17:14 -07:00
Scott Mitchell
0c839d9e0a EPOLL SelectStrategy
Motivation:
NIO now supports a pluggable select strategy, but EPOLL currently doesn't support this. We should strive for feature parity for EPOLL.

Modifications:
- Add SelectStrategy to EPOLL transport.

Result:
EPOLL transport supports SelectStategy.
2016-03-30 15:11:35 -07:00
Michael Nitschinger
5d76daf33b Allow to customize NIO (channel) select strategies.
Motivation:

Under high throughput/low latency workloads, selector wakeups are
degrading performance when the incoming operations are triggered
from outside of the event loop. This is a common scenario for
"client" applications where the originating input is coming from
application threads rather from the socket attached inside the
event loops.

As a result, it can be desirable to defer the blocking select
so that incoming tasks (write/flush) do not need to wakeup
the selector.

Modifications:

This changeset adds the notion of a generic SelectStrategy which,
based on its contract, allows the implementation to optionally
defer the blocking select based on some custom criteria.

The default implementation resembles the original behaviour, that
is if tasks are in the queue `selectNow()` and move on, and if no
tasks need to be processed go into the blocking select and wait
for wakeup.

The strategy can be customized per `NioEventLoopGroup` in the
constructor.

Result:

High performance client applications are now given the chance to
customize for how long the actual selector blocking should be
deferred by employing a custom select strategy.
2016-03-30 15:01:25 -07:00
fu.jian
0c733e1425 [#2363] Correctly null out SelectionKey[] when selectAgain
Motivation:

The prefix fix of #2363 did not correctly handle the case when selectAgain is true and so missed to null out entries.

Modifications:

Move the i++ from end of loop to beginning of loop

Result:

Entries in the array will be null out so allow to have these GC'ed once the Channel close
2016-01-08 09:04:10 +01:00
Trustin Lee
d0912f2709 Fix most inspector warnings
Motivation:

It's good to minimize potentially broken windows.

Modifications:

Fix most inspector warnings from our profile
Update IntObjectHashMap

Result:

Cleaner code
2014-07-02 19:55:07 +09:00
Norman Maurer
36b80c25f7 Correctly return from selector loop one a scheduled task is ready for processing
Motivation:

We use the nanoTime of the scheduledTasks to calculate the milli-seconds to wait for a select operation to select something. Once these elapsed we check if there was something selected or some task is ready for processing. Unfortunally we not take into account scheduled tasks here so the selection loop will continue if only scheduled tasks are ready for processing. This will delay the execution of these tasks.

Modification:

- Check if a scheduled task is ready after selecting
- also make a tiny change in NioEventLoop to not trigger a rebuild if nothing was selected because the timeout was reached a few times in a row.

Result:

Execute scheduled tasks on time.
2014-07-02 09:10:37 +02:00
Norman Maurer
2fa0b83e73 Cleanup comment / code 2014-06-27 21:36:52 +02:00
Norman Maurer
8bf8252060 [#2615] Correctly update SelectionKey after selector rebuild
Motivation:

When a select rebuild was triggered the reference to the SelectionKey is not updated in AbstractNioChannel. This will cause a CancelledKeyException later.

Modification:

Correctly update SelectionKey reference after rebuild

Result:

Fix exception
2014-06-27 17:21:34 +02:00
Norman Maurer
e8b5f19b82 Not cause busy loop when interrupt Thread of NioEventLoop
Motivation:
Because Thread.currentThread().interrupt() will unblock Selector.select() we need to take special care when check if we need to rebuild the Selector. If the unblock was caused by the interrupt() we will clear it and move on as this is most likely a bug in a custom ChannelHandler or a library the user makes use of.

Modification:
Clear the interrupt state of the Thread if the Selector was unblock because of an interrupt and the returned keys was 0.

Result:
No more busy loop caused by Thread.currentThread().interrupt()
2014-04-28 08:18:57 +02:00
Norman Maurer
88481131be [#2353] Use a privileged block to get ClassLoader and System property if needed
Motivation:
When using System.getProperty(...) and various methods to get a ClassLoader it will fail when a SecurityManager is in place.

Modifications:
Use a priveled block if needed. This work is based in the PR #2353 done by @anilsaldhana .

Result:
Code works also when SecurityManager is present
2014-04-08 14:12:25 +02:00
Norman Maurer
1087160fa7 [#2363] SelectedSelectionKeySet may hold strong reference to SelectionKey after Channel is closed
Motivation:
Because we not null out the array entry in the SelectionKey[] which is produced by SelectedSelectionKeySet.flip() we may end up with a few SelectionKeyreferences still hanging around here even after the Channel was closed. As these entries may be present at the end of the SelectionKey[] which is never updated for a long time as not enough SelectionKeys are ready.

Modifications:
Once we access the SelectionKey out of the SelectionKey[] we directly null it out.

Result:
Reference can be GC'ed right away once the Channel was closed.
2014-04-05 19:31:12 +02:00
Norman Maurer
d3ffa1b02b [#1259] Add optimized queue for SCMP pattern and use it in NIO and native transport
This queue also produces less GC then CLQ when make use of OneTimeTask
2014-02-27 13:28:37 +01:00
Vladimir Krivosheev
eb308cfff6 ability to use Executor instead of ThreadFactory 2014-02-13 16:14:41 -08:00
Norman Maurer
69a36b8bea Prettify exception message 2014-02-13 06:46:51 +01:00
Norman Maurer
62ebe88981 Allow to set IoRatio to 100% 2014-02-12 15:22:39 +01:00
Norman Maurer
80ed147652 [#2164] Only reregister SelectionKeys that are still valid 2014-01-29 07:18:29 +01:00
Trustin Lee
c9b7f1f1b5 Ensure the selector implementation can be instrumented before attempting instrumentation
- Fixes #1908
2013-10-11 12:08:51 +09:00
Norman Maurer
f034f90fb3 [#1836] Add comment to explain why read is triggered 2013-09-17 06:58:47 +02:00
Norman Maurer
80d30c3dd8 Small code improvements 2013-08-26 07:52:47 +02:00
Norman Maurer
4d0621855a Remove unused package private method and so remove some complexity 2013-08-09 11:44:41 +02:00
Norman Maurer
2871079c4a [#1557] Make the contract of Channel.Unsafe.flush() more clear
* Remove boolean parameter from Channel.Unsafe.flush() method
* Move NIO related things to AbstractNioChannel.NioUnsafe
2013-07-12 19:45:31 +02:00
Trustin Lee
99716993f6 Add a boolean parameter to Channel.Unsafe.flush() so that SelectionKey state check can be bypassed. 2013-07-12 20:14:50 +09:00
Trustin Lee
e10e9d38c4 Fix embarassing compilation error :-/ 2013-07-12 20:12:18 +09:00
Norman Maurer
2bda1b530a [#1523] Fix bug which lead to have SelectedKeys handled two times and so caused a NPE on heavy load 2013-07-04 16:15:33 +02:00
Trustin Lee
4b11aff08f Less confusing log messages for system properties
- Fixes #1502
2013-07-02 09:23:29 +09:00
Trustin Lee
3ce9ab2e72 Replace the sun.nio.ch.SelectorImpl.selectedKeys with faster one
- Yield much less garbage
- Slight performance gain (1~2%)
2013-06-11 00:00:55 +09:00
Norman Maurer
f7931af704 Re-add Unsafe.voidPromise() which can be used for Unsafe operations for which no notification should be done [#1375] 2013-05-25 14:35:22 +02:00
Norman Maurer
699ef0784e [#1317] Allow to use VoidPromise for flush(...), write(...) and sendFile(...)
* This also move rename Channel.Unsafe.voidFuture() to ChannelPropertyAccess.voidPromise()
2013-05-17 15:50:14 +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
Norman Maurer
067a2af700 Fix a few typos 2013-04-08 21:23:53 +02:00
Norman Maurer
4505e7f1b3 Make sure OP_WRITE is correctly cleared when using FileRegion and other NioTasks 2013-04-04 08:38:58 +02:00
Trustin Lee
0f3dc0409a Log various properties at startup time for easier diagnosis 2013-04-03 11:44:30 +09:00
Trustin Lee
19ffdd5c29 Revamp the selector auto rebuild checker
- Count the number of select() calls made to wait until reaching at the expected dead line, and rebuild selectors if too many select() calls were made.
2013-03-22 14:33:47 +09:00
Trustin Lee
69e5a0eb9c Log prematurly returning select() at DEBUG level and increase the minimum required consecutive premature returns to log 2013-03-22 12:59:47 +09:00
Trustin Lee
d525295d20 Revert NioEventLoop.hasTasks() which is not really true 2013-03-22 12:46:31 +09:00
Trustin Lee
34853e7ba0 Selector auto-rebuilder tweaks 2013-03-22 12:37:11 +09:00
Trustin Lee
f6e0df125a Allow disabling automatic selector rebuilding by specifing non-positive threshold 2013-03-22 11:50:53 +09:00