Commit Graph

474 Commits

Author SHA1 Message Date
Kevin Herron
ee3c8e0580 Test that CompositeByteBuf releases its components
Motivation:

In order to prevent a regression, add test case for a bug that caused a CompositeByteBuf to not release its components.

Modifications:

Add a test case that asserts a CompositeByteBuf's component buffers have indeed been released.

Result:

AbstractCompositeByteBuf gains a test case that will prevent future regressions.
2016-06-27 19:21:12 +02:00
agonigberg
3288cacf8d Pluggable resource leak detector
Allow users of Netty to plug in their own leak detector for the purpose
of instrumentation.

Motivation:

We are rolling out a large Netty deployment and want to be able to
track the amount of leaks we're seeing in production via custom
instrumentation. In order to achieve this today, I had to plug in a
custom `ByteBufAllocator` into the bootstrap and have it initialize a
custom `ResourceLeakDetector`. Due to these classes mostly being marked
`final` or having private or static methods, a lot of the code had to
be copy-pasted and it's quite ugly.

Modifications:

* I've added a static loader method for the `ResourceLeakDetector` in
`AbstractByteBuf` that tries to instantiate the class passed in via the
`-Dio.netty.customResourceLeakDetector`, otherwise falling back to the
default one.
* I've modified `ResourceLeakDetector` to be non-final and to have the
reporting broken out in to methods that can be overridden.

Result:

You can instrument leaks in your application by just adding something
like the following:

```java
public class InstrumentedResourceLeakDetector<T> extends
ResourceLeakDetector<T> {

    @Monitor("InstanceLeakCounter")
    private final AtomicInteger instancesLeakCounter;

    @Monitor("LeakCounter")
    private final AtomicInteger leakCounter;

    public InstrumentedResourceLeakDetector(Class<T> resource) {
        super(resource);
        this.instancesLeakCounter = new AtomicInteger();
        this.leakCounter = new AtomicInteger();
    }

    @Override
    protected void reportTracedLeak(String records) {
        super.reportTracedLeak(records);
        leakCounter.incrementAndGet();
    }

    @Override
    protected void reportUntracedLeak() {
        super.reportUntracedLeak();
        leakCounter.incrementAndGet();
    }

    @Override
    protected void reportInstancesLeak() {
        super.reportInstancesLeak();
        instancesLeakCounter.incrementAndGet();
    }
}
```
2016-06-20 11:14:44 +02:00
Xiaoyan Lin
9602535b7d Added isText to validate if a ByteBuf is compliant with the specified charset.
Motivation:

See #82.

Modifications:

- Added `isText` to validate if the given ByteBuf is compliant with the specified charset.
- Optimized for UTF-8 and ASCII. For other cases, `CharsetDecoder.decoder` is used.

Result:

Users can validate ByteBuf with given charset.
2016-06-20 07:32:05 +02:00
Norman Maurer
7137d22994 Ensure the correct wrapped buffer is released in AbstractPooledDerivedByteBuf.deallocate()
Motivation:

We need to first store a reference to the wrapped buffer before recycle the AbstractPooledDerivedByteBuf instance. This is needed as otherwise it is possible that the same AbstractPooledDerivedByteBuf is again obtained and init(...) is called before we actually have a chance to call release(). This leads to call release() on the wrong buffer.

Modifications:

Store a reference to the wrapped buffer before call recycle and call release on the previous stored reference.

Result:

Always release the correct wrapped buffer when deallocate the AbstractPooledDerivedByteBuf.
2016-06-06 09:49:42 +02:00
Norman Maurer
3a7dcde320 [#5224] Allow to use Unsafe.reallocateMemory(...) in UnpooledUnsafeNoCleanerDirectByteBuf.
Motivation:

If the user uses unsafe direct buffers with no cleaner we can use Unsafe.reallocateMemory(...) as optimization when we need to expand the buffer.

Modifications:

Use Unsafe.relocateMemory(...) in UnpooledUnsafeNoCleanerDirectByteBuf.

Result:

Less expensive expanding of buffers.
2016-06-04 19:21:41 +02:00
Norman Maurer
3d29bcfc8d Allow to create Unsafe ByteBuf implementations that not use a Cleaner to clean the native memory.
Motivation:

Using the Cleaner to release the native memory has a few drawbacks:

- Cleaner.clean() uses static synchronized internally which means it can be a performance bottleneck
- It put more load on the GC

Modifications:

Add new buffer implementations that can be enabled with a system flag as optimizations. In this case no Cleaner is used at all and the user must ensure everything is always released.

Result:

Less performance impact by direct buffers when need to be allocated and released.
2016-06-03 21:20:10 +02:00
Norman Maurer
db6b72da19 Add optimized version of setZero(...) / writeZero(...) for Unsafe*ByteBuf implementations
Motivation:

Unsafe offers a method to set memory to a specific value. This can be used to implement an optimized version of setZero(...) and writeZero(...)

Modifications:

Add implementation for all Unsafe*ByteBuf implementations.

Result:

Faster setZero(...) and writeZero(...)
2016-05-30 15:10:15 +02:00
Norman Maurer
7b25402e80 Add CompositeByteBuf.addComponent(boolean ...) method to simplify usage
Motivation:

At the moment the user is responsible to increase the writer index of the composite buffer when a new component is added. We should add some methods that handle this for the user as this is the most popular usage of the composite buffer.

Modifications:

Add new methods that autoamtically increase the writerIndex when buffers are added.

Result:

Easier usage of CompositeByteBuf.
2016-05-21 19:52:16 +02:00
Norman Maurer
2a14f74979 Ensure all methods are correctly override in *LeakAware*ByteBuf implementations
Motivation:

We missed to override a few methods and so some actions on the ByteBuf failed.

Modifications:

- Override all methods
- Add unit tests to ensure all is fixed.

Result:

All *LeakAware*ByteBuf have correct implementations
2016-05-21 07:28:13 +02:00
Norman Maurer
e10dca7601 Mark Recycler.recycle(...) deprecated and update usage.
Motivation:

Recycler.recycle(...) should not be used anymore and be replaced by Handle.recycle().

Modifications:

Mark it as deprecated and update usage.

Result:

Correctly document deprecated api.
2016-05-20 22:11:31 +02:00
Norman Maurer
d41f076419 Add more tests for PoolArenaMetric
Motivation:

We should add some more tests for PoolarenaMetric

Modifications:

Add more tests

Result:

Better test coverage for metrics
2016-05-20 21:56:36 +02:00
Norman Maurer
b83ffcc447 Add timeout to PooledByteBufAllocatorTest
Motivation:

Some tests in PooledByteBufAllocatorTest are blocking on a CountDownLatch. We should use a timeout on these tests so these will not block forever on a failure.

Modifications:

Add timeout param to @Test annotation

Result:

Have sane timeouts on tests.
2016-05-20 21:52:53 +02:00
Norman Maurer
43e91c2476 Correctly implement DefaultByteBufHolder.equals(...) and hashCode()
Motivation:

DefaultByteBufHolder.equals(...) and hashCode() should be implemented so it works correctly with instances that share the same content.

Modifications:

Add implementations and a unit-test.

Result:

Have correctly working equals(...) and hashCode() method
2016-05-20 21:43:40 +02:00
Trustin Lee
3a9f472161 Make retained derived buffers recyclable
Related: #4333 #4421 #5128

Motivation:

slice(), duplicate() and readSlice() currently create a non-recyclable
derived buffer instance. Under heavy load, an application that creates a
lot of derived buffers can put the garbage collector under pressure.

Modifications:

- Add the following methods which creates a non-recyclable derived buffer
  - retainedSlice()
  - retainedDuplicate()
  - readRetainedSlice()
- Add the new recyclable derived buffer implementations, which has its
  own reference count value
- Add ByteBufHolder.retainedDuplicate()
- Add ByteBufHolder.replace(ByteBuf) so that..
  - a user can replace the content of the holder in a consistent way
  - copy/duplicate/retainedDuplicate() can delegate the holder
    construction to replace(ByteBuf)
- Use retainedDuplicate() and retainedSlice() wherever possible
- Miscellaneous:
  - Rename DuplicateByteBufTest to DuplicatedByteBufTest (missing 'D')
  - Make ReplayingDecoderByteBuf.reject() return an exception instead of
    throwing it so that its callers don't need to add dummy return
    statement

Result:

Derived buffers are now recycled when created via retainedSlice() and
retainedDuplicate() and derived from a pooled buffer
2016-05-17 11:16:13 +02:00
Norman Maurer
30bb3094c1 [#5227] Fix race-condition in PooledByteBufAllocatorTest
Motivation:

PooledByteBufAllocatorTest.testNumThreadCachesWithNoDirrectArenas() had a race as it just used LockSupport.parkNanos(). We should better use a CountdownLatch and so be sure we really have init everything.

Modifications:

Replace LockSupport.parkNanos(...) with CountdownLatch usage

Result:

No more race in test.
2016-05-13 08:51:44 +02:00
Norman Maurer
2472d8c3cf [#5216] Correctly increment deallocationsHuge when call PoolArena.free
Motivation:

We called deallocationsHuge.decrement() but it needs to be increment()

Modifications:

Replace decrement() with increment()

Result:

Correct metrics.
2016-05-06 21:44:43 +02:00
Norman Maurer
9f5eb7d698 Add CharSequence operations to ByteBuf
Motivation:

Often users either need to read or write CharSequences to a ByteBuf. We should add methods for this to ByteBuf as we can do some optimizations for this depending on the implementation.

Modifications:

Add setCharSequence, writeCharSequence, getCharSequence and readCharSequence

Result:

Easier reading / writing of CharSequence with ByteBuf.
2016-05-06 16:52:00 +02:00
Carl Mastrangelo
cf07f984b1 Add @Deprecated when the javadoc says its deprecated
Motivation:

Reduce nag warnings when compiling, make it easier for IDEs to display what's deprecated.

Modifications:

Added @Deprecated in a few places

Result:

No more warnings.
2016-05-01 20:30:13 +02:00
Norman Maurer
d698746609 Add ByteBuf.asReadOnly()
Motivation:

We lately added ByteBuf.isReadOnly() which allows to detect if a buffer is read-only or not. We should add ByteBuf.asReadOnly() to allow easily access a read-only version of a buffer.

Modifications:

- Add ByteBuf.asReadOnly()
- Deprecate Unpooled.unmodifiableBuffer(Bytebuf)

Result:

More consistent api.
2016-04-14 10:51:20 +02:00
Jongyeol Choi
96455a9558 Implement codec-redis
Motivation:

- To encode/decode RESP (REdis Serialization Protocol) using Netty
- http://redis.io/topics/protocol

Modifications:

- Add RedisEncoder, RedisDecoder
- Add RedisBulkStringAggregator and RedisArrayAggregator
- Add tests

Result:

- Added codec-redis
- codec-redis can encode/decode RESP (REdis Serialization Protocol)
2016-04-14 10:23:16 +02:00
Norman Maurer
7d3ca7fb92 Fix IndexOutOfBoundsException when FixedCompositeByteBuf is constructed with an empty array.
Motivation:

When FixedCompositeByteBuf was constructed with new ByteBuf[0] and IndexOutOfboundsException was thrown.

Modifications:

Fix constructor

Result:

No more exception
2016-04-14 08:07:55 +02:00
Norman Maurer
4ddb81f36f Not cache SwappedByteBuf in AbstractByteBuf to reduce memory footprint.
Motivation:

We should not cache the SwappedByteBuf in AbstractByteBuf to reduce the memory footprint.

Modifications:

Not cache the SwappedByteBuf.

Result:

Less memory footprint.
2016-04-14 08:06:21 +02:00
Norman Maurer
2537880e5d Fix typo in exception message
Motivation:

Typo in exception message.

Modifications:

Fix the typo.

Result:

No more typo.
2016-04-14 08:03:35 +02:00
Trustin Lee
0b078314b2 Add ByteBuf.isReadOnly()
Motivation:

It is sometimes useful to determins if a buffer is read-only.

Modifications:

Add ByteBuf.isReadOnly()

Result:

One more feature
2016-04-13 21:41:27 +09:00
Trustin Lee
57063b6db0 Implement the ByteBuf methods that should have been overridden
Motivation:

Some ByteBuf implementations do not override all necessary methods,
which can lead to potentially sub-optimal behavior.

Also, SlicedByteBuf does not perform the range check correctly due to
missing overrides.

Modifications:

- Add missing overrides
- Use unwrap() instead of direct member access in derived buffers for
  consistency
- Merge unwrap0() into unwrap() using covariant return type
- Deprecate AbstractDerivedByteBuf and its subtypes, because they were
  not meant to be public

Result:

Correctness
2016-04-13 21:05:57 +09:00
Norman Maurer
69070c37ba ByteBuf.readBytes(...) should use the allocator of the buffer to create the new buffer. Related to [#5093]
Motivation:

ByteBuf.readBytes(...) uses Unpooled.buffer(...) internally which will use a heap ByteBuf and also not able to make use of the allocator which may be pooled. We should better make use of the allocator.

Modifications:

Use the allocator for thenew buffer.

Result:

Take allocator into account when copy bytes.
2016-04-09 20:28:17 +02:00
Norman Maurer
200ca39b5c Add PooledByteBufAllocator.dumpStats() which allows to obtain a human-readable status of the allocator.
Motiviation:

Sometimes it is useful to dump the status of the PooledByteBufAllocator and log it. Doing this is currently a bit cumbersome as the user needs to basically iterate through all the metrics and compose the String. we would better provide an easy way to do this.

Modification:

Add dumpStats() method.

Result:

Easier to get a view into the status of the allocator.
2016-04-09 19:16:53 +02:00
Norman Maurer
cfa258e096 PoolChunkList.allocate(...) should return false without the need to walk all the contained PoolChunks when the requested capacity is too big.
Motivation:

PoolChunkList.allocate(...) should return false without the need to walk all the contained PoolChunks when the requested capacity is larger then the capacity that can be allocated out of the PoolChunks in respect to the minUsage() and maxUsage() of the PoolChunkList.

Modifications:

Precompute the maximal capacity that can be allocated out of the PoolChunks that are contained in the PoolChunkList and use this to fast return from the allocate(...) method if an allocation capacity larger then that is requested.

Result:

Faster detection of allocations that can not be handled by the PoolChunkList and so faster allocations in general via the PoolArena.
2016-04-09 19:00:20 +02:00
Norman Maurer
2ae97946dd Allow to retrieve the number of active bytes per PoolArena.
Motivation:

To better understand how much memory is used by Netty for ByteBufs it is useful to understand how many bytes are currently active (allocated) per PoolArena.

Modifications:

- Add PoolArenaMetric.numActiveBytes()

Result:

The user is able to get better insight into the PooledByteBufAllocator.
2016-04-09 18:54:05 +02:00
Norman Maurer
787a55874b Cleanup PoolChunk and PoolArena
Motivation:

To make it easier to understand PoolChunk and PoolArena we should cleanup duplicated code.

Modifications:

- Move reused code into methods
- Use Math.max(...)

Result:

Cleaner code and easier to understand.
2016-04-09 18:47:40 +02:00
Norman Maurer
1b4a5609d3 Not try to allocate out of the PoolChunkList that contains only full PoolChunks
Motivation:

When doing a normal allocation in PoolArena we also tried to allocate out of the PoolChunkList that only contains completely full PoolChunks. This makes no sense as these are full anyway so an allocation will never work here and just gives a perf hit as we need to walk the whole list of PoolChunks in the list.

Modifications:

Not try to allocate from PoolChunkList that only contains full PoolChunks

Result:

Faster allocation times when a new PoolChunk must be created.
2016-04-09 18:39:56 +02:00
Norman Maurer
7b121c26ae Use Math.min(...) and Math.max(...) as these are intrinsics.
Motivation:

We should better use Math utilities as these are intrinsics. This is a cleanup for ea3ffb8536.

Modifications:

Use Math utilities.

Result:

Cleaner code and use of intrinsics.
2016-04-06 21:30:32 +02:00
Norman Maurer
88b093c481 PoolChunkList not correctly move PoolChunks when these are moved.
Motivation:

When a PoolChunk needs to get moved to the previous PoolChunkList because of the minUsage / maxUsage constraints we always just moved it one level which is incorrect and so could lead to have PoolChunks in the wrong PoolChunkList (in respect to their minUsage / maxUsage settings). This then could have the effect that PoolChunks are not released / freed in a timely fashion and so.

Modifications:

- Correctly move PoolChunks between PoolChunkLists, which includes moving it multiple "levels".
- Add unit test

Result:

Correctlty move the PoolChunk to PoolChunkList when it is freed, even if its multiple layers.
2016-04-06 11:52:23 +02:00
Norman Maurer
ea3ffb8536 Fix PoolChunkList.minUsage() and maxUsage() for head and tail
Motivation:

The PoolChunkList.minUsage() and maxUsage() needs to take special action to translate Integer.MIN_VALUE / MAX_VALUE as these are used internal for tail and head of the linked-list structure.

Modifications:

- Correct the minUsage() and maxUsage() methods.
- Add unit test.

Result:

Correct metrics
2016-04-06 10:03:28 +02:00
Norman Maurer
4e779cd6b0 Allow to disable leak detection for all buffers when using UnpooledByteBufAllocator.
Motivation:

Sometimes it is useful to allow to disable the leak detection of buffers if the UnpooledByteBufAllocator is used. This is for example true if the app wants to leak buffers into user code but not want to put the burden on the user to always release the buffer.

Modifications:

Add another constructor to UnpooledByteBufAllocator that allows to completely disable leak-detection for all buffers that are allocator out of the UnpooledByteBufAllocator.

Result:

It's possible to disable leak-detection when the UnpooledByteBufAllocator is used.
2016-04-05 13:17:16 +02:00
Norman Maurer
1d23e358b4 Only increment metric for huge / normal allocations after the allocation was really done.
Motivation:

We should only increment the metric for the huge / normal allocation after it is done. Also we should only decrement once deallocate.

Modifications:

- Move increment after the allocation.
- Fix deallocation metric and move it after deallocation

Result:

More correct metrics.
2016-04-05 12:00:44 +02:00
Norman Maurer
b32e07c75a PoolThreadCache uses wrong variable in IllegalArgumentException
Motivation:

PoolThreadCache includes the wrong value when throwing a IllegalArgumentException because of freeSweepAllocationThreshold.

Modifications:

Use the correct value.

Result:

Correct exception message.
2016-04-05 11:48:38 +02:00
Karas Lukáš
42419d918d Fix setBytes when source is read-only ByteBuffer and target is pooled buffer
Motivation:

The method setBytes creates temporary heap buffer when source buffer is read-only.
But this temporary buffer is not used correctly and may lead to data corruption.
This problem occurs when target buffer is pooled and temporary buffer
arrayOffset() is not zero.

Modifications:

Use correct arrayOffset when calling PlatformDependent.copyMemory.
Unit test was added to test this case.

Result:

Setting buffer content works correctly when target is pooled buffer and source
is read-only ByteBuffer.
2016-03-22 09:18:44 +01:00
Norman Maurer
8d499a2419 Fix calculation of PoolArena metrics after introducing a regression in 89da788fd2 2016-03-17 10:37:22 +01:00
Norman Maurer
daa4efcfef Add proper synchronization when access metrics.
Motivation:

We also need to add synchronization when access fields to ensure we see the latest updates.

Modifications:

Add synchronization when read fields that are written concurrently.

Result:

Ensure correct visibility of updated.
2016-03-17 09:05:48 +01:00
Xiaoyan Lin
01835fdf18 Add LineEncoder to append a line separator automatically
Motivation:

See #1811

Modifications:

Add LineEncoder and LineSeparator

Result:

The user can use LineEncoder to write a String with a line separator automatically
2016-03-16 20:31:01 +01:00
Norman Maurer
6796604f46 Remove double spacing
Motivation:

We had some double spacing in the methods which should be removed to keep things consistent.

Modifications:

Remove redundant spaces.

Result:

Cleaner / consistent coding style.
2016-03-16 10:25:48 +01:00
Norman Maurer
7d12333c38 Add final keyword which was missing in 47b598e6ce
Motivation:

The two fields should have final keyword.

Modifications:

Add final keyword

Result:

Cleaner code.
2016-03-16 10:25:00 +01:00
buchgr
83c349ffa9 Fix wrong use of assertTrue in unit test.
Motivation:

My previous commit b88a980482 introduced a flawed unit test,
that executes an assertion in a different thread than the test thread.
If this assertion fails, the test doesn't fail.

Modifications:

Replace the assertion by a proper workaround.

Result:

More correct unit test
2016-03-15 16:02:33 +01:00
buchgr
b88a980482 Change arena to thread cache mapping algorithm to be closer to ideal.
Motivation:
Circular assignment of arenas to thread caches can lead to less than optimal
mappings in cases where threads are (frequently) shutdown and started.

Example Scenario:
There are a total of 2 arenas. The first two threads performing an allocation
would lead to the following mapping:

Thread 0 -> Arena 0
Thread 1 -> Arena 1

Now, assume Thread 1 is shut down and another Thread 2 is started. The current
circular assignment algorithm would lead to the following mapping:

Thread 0 -> Arena 0
Thread 2 -> Arena 0

Ideally, we want Thread 2 to use Arena 1 though.

Presumably, this is not much of an issue for most Netty applications that do all
the allocations inside the eventloop, as eventloop threads are seldomly shut down
and restarted. However, applications that only use the netty-buffer package
or implement their own threading model outside the eventloop might suffer from
increased contention. For example, gRPC Java when using the blocking stub
performs some allocations outside the eventloop and within its own thread pool
that is dynamically sized depending on system load.

Modifications:

Implement a linear scan algorithm that assigns a new thread cache to the arena
that currently backs the fewest thread caches.

Result:

Closer to ideal mappings between thread caches and arenas. In order to always
get an ideal mapping, we would have to re-balance the mapping whenever a thread
dies. However, that's difficult because of deallocation.
2016-03-15 14:16:34 +01:00
buchgr
35771dd1cd Fix race in PoolArena.allocate. Fixes #4829
Motivation:

The statistic counters PoolArena.(allocationsTiny|allocationsSmall) are
not protected by a per arena lock, but by a per size class lock. Thus,
two concurrent allocations of different size (class) could lead to a
race and ultimately to wrong statistics.

Modifications:

Use a thread-safe LongCounter instead of a plain long data type.

Result:

Fewer data races.
2016-03-14 08:57:46 +01:00
Xiaoyan Lin
e2d4e22243 Add CharsetUtil.encoder/decoder() methods
Motivation:

See #3321

Modifications:

1. Add CharsetUtil.encoder/decoder() methods
2. Deprecate CharsetUtil.getEncoder/getDecoder() methods

Result:

Users can use new CharsetUtil.encoder/decoder() to specify error actions
2016-03-07 10:48:31 +00:00
Scott Mitchell
94f27be59b ByteBufUtil writeUtf8 and writeAscii helper methods
Motivation:
Utility methods in ByteBufUtil to writeUtf8 and writeAscii expect a buffer to already be allocated. If the user does not have a buffer allocated they have to know details of the encoding in order to know the size of the buffer to allocate.

Modifications:
- Add writeUtf8 and writeAscii which take a ByteBufAllocator and allocate a ByteBuf of the correct size for the user

Result:
ByteBufUtil methods which are easier to use if the user doesn't already have a ByteBuf.
2016-02-29 10:09:06 +01:00
Norman Maurer
74495fd27f Add advanced leakdetection for methods introduced by [#4842]
Motivation:

[#4842] introduced 4 new methods but missed to implement advanced leak detection for these.

Modifications:

Correctly implement advanced leak detection for these methods.

Result:

Advanced leak detection works for all methods as expected.
2016-02-17 09:40:42 -08:00
Xiaoyan Lin
ccb0870600 Add methods with position independent FileChannel calls to ByteBuf
Motivation

See ##3229

Modifications:

Add methods with position independent FileChannel calls to ByteBuf and its subclasses.

Results:

The user can use these new methods to read/write ByteBuff without updating FileChannel's position.
2016-02-14 20:37:37 -08:00