Commit Graph

896 Commits

Author SHA1 Message Date
Norman Maurer fd0d06ee39
Replace reflection usage with MethodHandles when performance matters (#10097)
Motivation:

As we have java8 as a minimum target we can use MethodHandles. We should do so when we expect to have a method called multiple times.

Modifications:

- Replace usage of reflection with MethodHandles where it makes sense
- Remove some code which was there to support java < 8

Result:

Faster code
2020-03-11 21:04:40 +01:00
feijermu 217365dd65 Replace several magic numbers. (#10094)
Motivation:

Magic numbers seem hard to read or understand.

Modification:

Replace several magic numbers with named constants.

Result:

Improve readability and make it easier to maintain.
2020-03-09 11:56:00 +01:00
feijermu f07115c2a6 Add a log level check simply before logging. (#10093)
Motivation:

ThrowableUtil.stackTraceToString is an expensive method call. So I think a log level check before this logging statement is quite needed especially in a environment with the warning log disabled.

Modification:

Add log level check simply before logging.

Result:

Improve performance in a environment with the warning log disabled.
2020-03-09 08:48:56 +01:00
Norman Maurer 118e1c66dc Add log level check simply before logging. (#10080)
Motivation:

In general, we will close the debug log in a product environment. However, logging without external level check may still affect performance as varargs will need to allocate an array.

Modification:

Add log level check simply before logging.

Result:

Improve performance slightly in a product environment.
2020-03-05 14:46:22 +01:00
Norman Maurer 4a07f1cd10 More strict parsing of initial line / http headers (#10058)
Motivation:

Our parsing of the initial line / http headers did treat some characters as separators which should better trigger an exception during parsing.

Modifications:

- Tighten up parsing of the inital line by follow recommentation of RFC7230
- Restrict separators to OWS for http headers
- Add unit test

Result:

Stricter parsing of HTTP1
2020-02-26 10:01:41 +01:00
Norman Maurer 639f5c9d48 NetworkInterface.getByInetAddress() may return null on Android platform (#10056)
Motivation:

NetworkInterface.getByInetAddress() may return null on Android. This is incorrect by the API but still happens. To help our users we should provide a workaround

Modifications:

Just return an empty Enumeration when null is returned.

Result:

Fixes https://github.com/netty/netty/issues/10045
2020-02-25 09:37:54 +01:00
feijermu 9cbfcf39da Add a null check to NetUtil. sysctlGetInt(...) (#10027)
Motivation:

BufferedReader.readLine() may return null and cause a NPE.

Modification:

Simply add a null check.

Result:

If BufferedReader.readLine() returns null, the sysctlGetInt will just return null rather than cause NPE.
2020-02-14 09:12:14 +01:00
Norman Maurer 0cd4109f64 java.security.AccessControlException: access denied ("java.io.FilePermission" "/etc/os-release" "read") (#10018)
Motivation:

Modifications:

- Wrap the code and execute with an AccessController
- Ignore SecurityException (by just logging it)
- Add some more debug logging

Result:

Fixes https://github.com/netty/netty/issues/10017
2020-02-13 12:02:02 +01:00
Ruwei a6393c3d01 fix bug: scheduled tasks may not be executed (#9980)
Motivation:

If there was always a task in the taskQueue of GlobalEvenExecutor, scheduled tasks in the
scheduledTaskQueue will never be executed.

Related to  #1614

Modifications:

fix bug in GlobalEventExecutor#takeTask

Result:

fix bug
2020-01-31 11:10:21 +01:00
Johno Crawford 7413372c01 SSL / BlockHound works out of the box with the default SSL provider (#9969)
Motivation:

JDK is the default SSL provider and internally uses blocking IO operations.

Modifications:

Add allowBlockingCallsInside configuration for SslHandler runAllDelegate function.

Result:

When BlockHound is installed, SSL works out of the box with the default SSL provider.

Co-authored-by: violetagg <milesg78@gmail.com>
2020-01-30 11:50:15 +01:00
Norman Maurer 6a43807843
Use lambdas whenever possible (#9979)
Motivation:

We should update our code to use lamdas whenever possible

Modifications:

Use lambdas when possible

Result:

Cleanup code for Java8
2020-01-30 09:28:24 +01:00
时无两丶 6158c40f45 Introduce `needReport` for `ResourceLeakDetector`. (#9910)
Motivation:

We can extend `ResourceLeakDetector` through `ResourceLeakDetectorFactory`, and then report the leaked information by covering `reportTracedLeak` and `reportUntracedLeak`. However, the behavior of `reportTracedLeak` and `reportUntracedLeak` is controlled by `logger.isErrorEnabled()`, which is not reasonable. In the case of extending `ResourceLeakDetector`, we sometimes need `needReport` to always return true instead of relying on `logger.isErrorEnabled ()`.

Modification:

introduce `needReport` method and let it be `protected`

Result:

We can control the report leak behavior.
2020-01-10 05:22:05 +01:00
Francesco Nigro 1e4f0e6a09 Faster decodeHexNibble (#9896)
Motivation:

decodeHexNibble can be a lot faster using a lookup table

Modifications:

decodeHexNibble is made faster by using a lookup table

Result:

decodeHexNibble is faster
2019-12-23 21:16:44 +01:00
Ikhun Um f60c13a57f Fix typos in javadocs (#9900)
Motivation:

Javadocs should have no typos.

Modifications:

Fix two typos

Result:

Less typos.
2019-12-23 08:34:28 +01:00
Norman Maurer 7931501769 Ignore inline comments when parsing nameservers (#9894)
Motivation:

The resolv.conf file may contain inline comments which should be ignored

Modifications:

- Detect if we have a comment after the ipaddress and if so skip it
- Add unit test

Result:

Fixes https://github.com/netty/netty/issues/9889
2019-12-18 21:14:17 +01:00
Robert Mihaly d7bb05b1ac Ensure scheduled tasks are executed before shutdown (#9858)
Motivation:

In #9603 the executor hung on shutdown because of an abandoned task
on another executor the first was waiting for.

Modifications:

This commit modifies the executor shutdown sequence to include
switching to SHUTDOWN state and then running all remaining tasks.
This ensures that no more tasks are scheduled after SHUTDOWN and
the last pass of running remaining tasks will take it all.
Any tasks scheduled after SHUTDOWN will be rejected.

This change preserves the functionality of graceful shutdown with
quiet period and only adds one more pass of task execution after
the default shutdown process has finished and the executor is
ready for termination.

Result:

After this change tasks that succeed to be added to the executor will
be always executed. Tasks which come late will be rejected instead of
abandoned.
2019-12-11 11:33:59 +01:00
Norman Maurer ff8846f1b5
Replace ObjectUtil.checkNonNull(...) with Objects.requireNonNull(...) (#9864)
Motivation:

We should use Objects.requireNonNull(...) as we require java8

Modifications:

Replace ObjectUtil.checkNonNull(...) with Objects.requireNonNull(...)

Result:

Code cleanup
2019-12-10 11:27:32 +01:00
时无两丶 5223217121 Replace map with set. (#9833)
Motivation:
Replace Map with Set. `reportedLeaks` has better semantics as a Set, and if it is a Map, it seems that the value of this Map has no meaning to us.

Modifications:

Use Set.

Result:
Cleaner code
2019-12-04 13:57:01 +01:00
Nick Hill d3011d4f5b Use interval instead of mask comparison for Recycler ratio (#9748)
Motivation

The recycling ratio is currently implemented by comparing with a masked
count. The mask operation is not free and also not necessary.

Modification

Change the count(s) to just iterate over the corresponding interval,
which requires only a comparison and no mask.

Also make "first time recycle" behaviour consistent and revert change to
RecyclerTest made in #9727.

Result

Less recycling overhead
2019-11-05 15:21:09 +01:00
Norman Maurer f0e1628426 Cleanup Recycler to better encapsulate stuff (#9739)
Motivation:

We can move some methods etc to make encapsulation better in Recycler

Modifications:

Move / rename methods to make usage more clear

Result:

Code cleanup
2019-11-04 17:44:12 +01:00
Norman Maurer e77b9104d7 Enforce ratioMask also for WeakOrderQueue (#9727)
Motivation:

At the moment we only enfore ratioMask for the Stack which means that we only guard against recycle burts when recycled from the same Thread. We should also enforce the ratioMask in the WeakOrderQueue so we also guard against the bursts when recycle from other threads.

Modifications:

- Keep counter in WeakOrderQueue to enforce ratioMask as well
- Adjust unit test

Result:

Better guard against recycle bursts which could pollute the heap unnecessary.
2019-11-01 07:10:57 +01:00
Nick Hill 7c543a48e5 Avoid synthetic methods in Recycler (#9736)
Motivation

Currently the visibility of the various Recycler inner classes and their
fields isn't optimal. Some private members are accessed by other classes
resulting in synthetic methods, and other non-private classes/members
are only accessed privately and so can be made private.

Modifications

- Increase/reduce visibility of various fields/methods/classes within
Recycler
- Have WeakOrderQueue extend WeakReference<Thread> to eliminate the
owner field
- Change local DefaultHandle var to DefaultHandle<?> to avoid raw type
compiler warning

Result

Tidier code, fewer implicit methods on hot paths (reducing inlining
depths)
2019-10-31 11:28:11 +01:00
Norman Maurer e816018569 Remove usage of finalizer in Recycler (#9726)
Motivation:

We currently use a finalizer to ensure we correctly return the reserved back to the Stack but this is not really needed as we can ensure we return it when needed before dropping the WeakOrderQueue

Modifications:

Use explicit method call to ensure we return the reserved space back before dropping the object

Result:

Less finalizer usage and so less work for the GC
2019-10-31 09:58:43 +01:00
Norman Maurer 29761a91bd Correctly update size of the Stack before doing any validation in Recycler (#9731)
Motivation:

We null out the element in the array after we decrement the current size of the Stack but not directly write back the updated size to the stored field. This is problematic as we do some validation before we write it back and so may never do so if the validation fails. This then later can lead to have null objects returned where not expected

Modifications:

Update size directly after null out object

Result:

No more unexpected null value possible
2019-10-31 09:52:28 +01:00
Bennett Lynch 47f82b6b20 Prefer Log4J2 over Log4J1 for default InternalLoggerFactory (#9734)
##Motivation

The InternalLoggerFactory attempts to instantiate different logger
implementations to discover what is available on the class path,
accepting the first implementation that does not throw an exception.

Currently, the default ordering will attempt to instantiate a Log4j1
logger before Log4j2. For environments where both Log4j1 and Log4j2 are
available, this will result in using the older version. It seems that it
would be more intuitive to prefer the newer version, when possible.

##Modifications

Change the default ordering to attempt to use the Log4J2LoggerFactory
before the Log4JLoggerFactory.

##Result

For environments where both Log4j1 and Log4j2 are available on the class
path (but Slf4J is not available), Netty will now use Log4j2 instead of
Log4j1.
2019-10-30 19:36:03 +01:00
Norman Maurer dc104de503 Don't pollute FastThreadLocal for Threads with WeakHashMap if maxDelayedQueues == 0 (#9722)
Motivation:

If maxDelayedQueues == 0 we should never put any WeakHashMap into the FastThreadLocal for a Thread.

Modifications:

Check if maxDelayedQueues == 0 and if so return directly. This will ensure we never call FastThreadLocal.initialValue() in this case

Result:

Less overhead / memory usage when maxDelayedQueues == 0
2019-10-28 18:36:38 +01:00
Norman Maurer 4be554a21f Hide Recycler implemention to allow experimenting with different implementions of an Object pool (#9715)
Motivation:

At the moment we directly extend the Recycler base class in our code which makes it hard to experiment with different Object pool implementation. It would be nice to be able to switch from one to another by using a system property in the future. This would also allow to more easily test things like https://github.com/netty/netty/pull/8052.

Modifications:

- Introduce ObjectPool class with static method that we now use internally to obtain an ObjectPool implementation.
- Wrap the Recycler into an ObjectPool and return it for now

Result:

Preparation for different ObjectPool implementations
2019-10-26 09:43:21 +02:00
Norman Maurer 68413574aa Guard against busy spinning in HashedWheelTimer when using windows and a tickDuration of 1 (#9714)
Motivation:

We do not correct guard against the gact that when applying our workaround for windows we may end up with a 0 sleep period. In this case we should just sleep for 1 ms.

Modifications:

Guard agains the case when our calculation will produce 0 as sleep time on windows

Result:

Fixes https://github.com/netty/netty/issues/9710.
2019-10-25 20:14:31 +02:00
Norman Maurer 5949e193ce Fix compilation error introduced by 2854c2c473 2019-10-25 17:47:27 +02:00
Sergei Egorov 2854c2c473 Add BlockHound integration that detects blocking calls in event loops (#9687)
Motivation:

Netty is an asynchronous framework.
If somebody uses a blocking call inside Netty's event loops,
it may lead to a severe performance degradation.
BlockHound is a tool that helps detecting such calls.

Modifications:

This change adds a BlockHound's SPI integration that marks
threads created by Netty (`FastThreadLocalThread`s) as non-blocking.
It also marks some of Netty's internal methods as whitelisted
as they are required to run the event loops.

Result:

When BlockHound is installed, any blocking call inside event loops
is intercepted and reported (by default an error will be thrown).
2019-10-25 15:14:44 +02:00
Norman Maurer ec8e8bd515
Fix event loop shutdown timing fragility (#9639)
Motivation

The current event loop shutdown logic is quite fragile and in the
epoll/NIO cases relies on the default 1 second wait/select timeout that
applies when there are no scheduled tasks. Without this default timeout
the shutdown would hang indefinitely.

The timeout only takes effect in this case because queued scheduled
tasks are first cancelled in
SingleThreadEventExecutor#confirmShutdown(), but I _think_ even this
isn't robust, since the main task queue is subsequently serviced which
could result in some new scheduled task being queued with much later
deadline.

It also means shutdowns are unnecessarily delayed by up to 1 second.

Modifications

- Add/extend unit tests to expose the issue
- Adjust SingleThreadEventExecutor shutdown and confirmShutdown methods
to explicitly add no-op tasks to the taskQueue so that the subsequent
event loop iteration doesn't enter blocking wait (as looks like was
originally intended)

Results

Faster and more robust shutdown of event loops, allows removal of the default wait timeout.
This is a port of https://github.com/netty/netty/pull/9616
2019-10-08 12:00:59 +04:00
时无两丶 5d1414a8a9 Double check `size` to avoid `ArrayIndexOutOfBoundsException` (#9609)
Motivation:

Recycler$Stack.pop will occurs `ArrayIndexOutOfBoundsException` in some race cases, we should double check `size` even after `scavenge` called.

Modifications:

Double check `size` after `scavenge`

Result:

avoid ArrayIndexOutOfBoundsException in `pop`
2019-09-26 21:55:24 +02:00
Norman Maurer 14a820d5fa
Always notify FutureListener via the EventExecutor (#9489)
Motiviation:

A lot of reentrancy bugs and cycles can happen because the DefaultPromise will notify the FutureListener directly when completely in the calling Thread if the Thread is the EventExecutor Thread. To reduce the risk of this we should always notify the listeners via the EventExecutor which basically means that we will put a task into the taskqueue of the EventExecutor and pick it up for execution after the setSuccess / setFailure methods complete the promise.

Modifications:

- Always notify via the EventExecutor
- Adjust test to ensure we correctly account for this
- Adjust tests that use the EmbeddedChannel to ensure we execute the scheduled work.

Result:

Reentrancy bugs related to the FutureListeners cant happen anymore.
2019-09-24 09:10:59 +02:00
wyzhang bfe18bcb3c Fix a bug introduced by 79706357c7 which can cause thread to spin in an infinite loop. (#9579)
Motivation:
peek() is implemented in a similar way to poll() for the mpsc queue, thus it is more like a consumer call.
It is possible that we could have multiple thread call peek() and possibly one thread calls poll() at at the same time.
This lead to multiple consumer scenario, which violates the multiple producer single consumer condition and could lead to spin in an infinite loop in peek()

Modification:
Use isEmpty() instead of peek() to check if task queue is empty

Result:
Dont violate the mpsc semantics.
2019-09-19 12:03:27 +02:00
Norman Maurer fafde4aeec No need to explicit use the AccessController when SystemPropertyUtil is used (#9577)
Motivation:

SystemPropertyUtil already uses the AccessController internally so not need to wrap its usage with AccessController as well.

Modifications:

Remove explicit AccessController usage when SystemPropertyUtil is used.

Result:

Code cleanup
2019-09-19 08:50:36 +02:00
Andrey Mizurov f26840478a Fix HttpContentEncoder does not handle multiple Accept-Encoding (#9557)
Motivation:
At the current moment HttpContentEncoder handle only first value of multiple accept-encoding headers.

Modification:

Join multiple accept-encoding headers to one separated by comma.

Result:

Fixes #9553
2019-09-11 08:50:43 +02:00
Nick Hill 6423e80932 Avoid redundant volatile read in DefaultPromise#get() (#9547)
Motivation

Currently every call to get() on a promise results in two reads of the
volatile result field when one would suffice. Maybe this is optimized
away but it seems sensible not to rely on that.

Modification

Reimplement get() and get(...) in DefaultPromise to reduce volatile access.

Result

Fewer volatile reads.
2019-09-09 10:03:30 +02:00
Nick Hill 0280bd2063 Avoid CancellationException construction in DefaultPromise (#9534)
Motivation

problem with Throwable#addSuppressed() raised in #9151. This introduced
a performance issue when promises are cancelled at a high frequency due
to the construction cost of CancellationException at the time that
DefaultPromise#cancel() is called.

Modifications

- Reinstate the prior static CANCELLATION_CAUSE_HOLDER but use it just
as a sentinel to indicate cancellation, constructing a new
CancellationException only if/when one needs to be explicitly
returned/thrown
- Subclass CancellationException, overriding fillInStackTrace() to
minimize the construction cost in these cases

Result

Promises are much cheaper to cancel. Fixes #9522.
2019-09-05 11:10:55 +02:00
Xiaoqin Fu 88aa12cc1a Remove extra checks to fix #9456 (#9523)
Motivation:

There are some extra log level checks (logger.isWarnEnabled()).

Modification:

Remove log level checks (logger.isWarnEnabled()) from io.netty.channel.epoll.AbstractEpollStreamChannel, io.netty.channel.DefaultFileRegion, io.netty.channel.nio.AbstractNioChannel, io.netty.util.HashedWheelTimer, io.netty.handler.stream.ChunkedWriteHandler and io.netty.channel.udt.nio.NioUdtMessageConnectorChannel

Result:

Fixes #9456
2019-08-30 10:40:04 +02:00
szh c227053c3b Fix log format in HashedWheelTimer (#9507)
Motivation:

log message did not correctly use `{}`

Modification:

replace `%d` by `{}`

Result:

The log is correct.
2019-08-26 08:55:15 +02:00
Antony T Curtis 188c927576 AsciiString contentEqualsIgnoreCase fails when arrayOffset is non-zero (#9477)
Motivation:

AsciiString.contentEqualsIgnoreCase may return true for non-matching strings of equal length when offset is non zero.

Modifications:

- Correctly take offset into account
- Add unit test

Result: 

Fixes #9475
2019-08-17 09:57:40 +02:00
Nico Kruber d285623925 Try to load native linux libraries with matching classifier first (#9411)
Motivation:

Users' runtime systems may have incompatible dynamic libraries to the ones our
tcnative wrappers link to. Unfortunately, we cannot determine and catch these
scenarios (in which the JVM crashes) but we can make a more educated guess on
what library to load and try to find one that works better before crashing.

Modifications:

1) Build dynamically linked openSSL builds for more OSs (netty-tcnative)
2) Load native linux libraries with matching classifier (first)

Result:

More developers / users can use the dynamically-linked native libraries.
2019-08-12 08:48:58 +02:00
Per Lundberg eef72b022a Future.java: Fix typos in Javadoc (#9391)
Motivation:

Docs should have no typos

Modifications:

Fix a few typos

Result:

More correct docs.
2019-07-24 07:38:08 +02:00
YuanHu 90b788bef7 Recycler availableSharedCapacity will be slowly exhausted due missing reclaimSpace(...) call (#9394)
Motivation:

We did miss to call reclaimSpace(...) in one case which can lead to the situation of having the Recycler to not correctly reclaim space and so just create new objects when not needed.

Modifications:

Correctly call reclaimSpace(...)

Result:

Recycler correctly reclaims space in all situations.
2019-07-21 21:07:12 +02:00
Dmitriy Dumanskiy 390fa95f32 prefer instanceOf instead of getClass() (#9366)
Motivation:

`instanceOf` doesn't perform null check like `getClass()` does. So `instanceOf` may be faster. However, it not true for all cases, as C2 could eliminate these null checks for `getClass()`.

Modification:

Replaced `string.getClass() == AsciiString.class` with `string instanceof AsciiString`.

Proof:

```
@BenchmarkMode(Mode.Throughput)
@Fork(value = 1)
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1, batchSize = 1000)
@Measurement(iterations = 10, time = 1, batchSize = 1000)
public class GetClassInstanceOf {

    Object key;

    @Setup
    public void setup() {
        key = "123";
    }

    @Benchmark
    public boolean getClassEquals() {
        return key.getClass() == String.class;
    }

    @Benchmark
    public boolean instanceOf() {
        return key instanceof String;
    }

}
```

```
Benchmark                           Mode  Cnt       Score      Error  Units
GetClassInstanceOf.getClassEquals  thrpt   10  401863.130 ± 3092.568  ops/s
GetClassInstanceOf.instanceOf      thrpt   10  421386.176 ± 4317.328  ops/s
```
2019-07-16 21:25:59 +02:00
jingene af614e4d6e Change the netty.io homepage scheme(http -> https) (#9344)
Motivation:

Netty homepage(netty.io) serves both "http" and "https".
It's recommended to use https than http.
Modification:

I changed from "http://netty.io" to "https://netty.io"
Result:

No effects.
2019-07-09 21:10:14 +02:00
jimin d54678d645 Remove unnecessary code (#9303)
Motivation:

There are is some unnecessary code (like toString() calls) which can be cleaned up.

Modifications:

- Remove not needed toString() calls
- Simplify subString(...) calls
- Remove some explicit casts when not needed.

Result:

Cleaner code
2019-07-04 09:02:24 +02:00
jimin 411b6a56b5 remove unused imports (#9287)
Motivation:

Some imports are not used

Modification:

remove unused imports

Result:

Code cleanup
2019-06-26 21:16:16 +02:00
Nick Hill ed23cfae5e Simplify SingleThreadEventExecutor.awaitTermination() implementation (#9081)
Motivation

A Semaphore is currently dedicated to this purpose but a simple
CountDownLatch will do.

Modification

Remove private threadLock Semaphore from SingleThreadEventExecutor and just use a CountDownLatch.

Also eliminate use of PlatformDependent.throwException() in startThread
method, and combine some nested if clauses.

Result

Cleaner EventLoop termination notification.
2019-05-27 16:09:41 +02:00
Norman Maurer ed61e5f543 Only use static Exception instances when we can ensure addSuppressed … (#9152)
Motivation:

OOME is occurred by increasing suppressedExceptions because other libraries call Throwable#addSuppressed. As we have no control over what other libraries do we need to ensure this can not lead to OOME.

Modifications:

Only use static instances of the Exceptions if we can either dissable addSuppressed or we run on java6.

Result:

Not possible to OOME because of addSuppressed. Fixes https://github.com/netty/netty/issues/9151.
2019-05-17 22:42:53 +02:00