dawdler-serialization
Serialization module, providing two serialization implementations: JDK and Kryo.
1. Adding the dependency
<groupId>club.dawdler</groupId>
<artifactId>dawdler-serialization</artifactId>
2. Extending serialization via SPI
Implement the club.dawdler.serializer.Serializer interface; the byte identifier returned by the key method must be unique. Two implementations are built in: jdk is 1 and kryo is 2. The identifier corresponds to the serializer attribute of the server-channel-group node in client-conf.xml.
Create a file named club.dawdler.serializer.Serializer under resources/META-INF/services containing the fully qualified name of the implementation class. See the SPI file at the same path in this module for reference.
A newly added class must be packaged into dawdler-serialization.jar, or the new jar must be placed under dawdler-server/bin (the client side needs the same).
3. Extending via listeners
SerializeDecider provides a register method, which can be used by a listener at startup. It must be set on both the client and the server; not recommended.
4. Kryo deserialization security configuration
By default Kryo allows deserialization of any class on the classpath, which carries deserialization attack risk. This module provides a whitelist-based SecureClassResolver that validates the class name before deserialization.
4.1 Switch
-Ddawdler.serializer.kryo.secure.enabled=true
Enabled by default. A class not in the whitelist causes a KryoException to be thrown and a warn log to be recorded. If existing business code is incompatible, it can be disabled:
-Ddawdler.serializer.kryo.secure.enabled=false
The client and server must use the same setting; otherwise a class written by one side is blocked on the other side.
4.2 Filtering rules
Validated in order, stopping at the first match:
- Blacklisted concrete class name - reject on match
- Blacklisted package prefix - reject on match
- Whitelisted package prefix - allow on match
- No match at all - reject
Default whitelisted package prefixes: java.lang., java.util., java.math., java.time., java.sql., club.dawdler.
The default blacklisted package prefixes and class names form the security baseline shared by both the Kryo and JDK channels (see chapter 5, maintained in one place by SerializationSecurityBaseline); the system property of either channel can only append entries, never remove defaults.
Default blacklisted package prefixes: java.lang.reflect., java.lang.invoke., java.net., java.rmi., javax.script., javax.management., javax.naming., javax.sql.rowset., javax.annotation., java.beans., com.sun., sun., jdk.proxy.
Default blacklisted class names: java.lang.Runtime, java.lang.ProcessBuilder, java.lang.ProcessImpl, java.lang.ProcessEnvironment, java.lang.Thread, java.lang.ClassLoader, java.lang.System, java.lang.Shutdown, java.lang.Void
Array types (such as [Ljava.lang.Runtime;) are decomposed into their element type and validated recursively to prevent bypasses.
4.3 Appending whitelist and blacklist entries
Custom business classes require appending whitelisted package prefixes:
-Ddawdler.serializer.kryo.whitelist.packages=com.example.dto.,com.example.entity.
Appending blacklisted class names (comma-separated):
-Ddawdler.serializer.kryo.blacklist.classes=com.example.Dangerous,com.example.Unsafe
4.4 Throwable restrictions
java.lang.Throwable uses SafeThrowableSerializer by default, which serializes only message/cause/stackTrace (stack depth capped at 1024). Other fields of custom Throwables are not retained after deserialization, so both sides must be upgraded together.
5. JDK deserialization filtering (ObjectInputFilter)
JDK native serialization (identifier 1) goes through ObjectInputStream, which without filtering can instantiate any class on the classpath. This module installs a JDKDeserializationFilter on every stream; it takes effect without configuration.
5.1 Always-on protection (cannot be disabled)
- Blacklisted class names: the security baseline shared with 4.2 (the same constants, not a copy)
- Blacklisted package prefixes: the security baseline shared with 4.2 (including
java.net.; when process-level settings such asjdk.serialFilteralso exist on the JDK side, they are combined via merge) - Structural limits: nesting depth <= 256, declared length of a single array <= 10000000, total references <= 1000000
Array types are likewise decomposed and validated recursively. Rejection happens before readObject instantiation; the stream is aborted with InvalidClassException and a warn log is recorded.
When a filter allows a class it returns UNDECIDED rather than ALLOWED, so it is merged with the process-level jdk.serialFilter and a rejection from either side takes effect.
5.2 Strict whitelist mode
# Enabled by default; disable only when existing DTOs are not in the whitelist
-Ddawdler.serializer.jdk.secure.enabled=false
In strict mode only classes with whitelisted package prefixes are allowed (the blacklist takes precedence). The default whitelisted package prefixes are the same as in 4.2.
Custom business classes need to be appended:
-Ddawdler.serializer.jdk.whitelist.packages=com.example.dto.,com.example.entity.
5.3 Configuration properties
| Property | Default | Description |
|---|---|---|
dawdler.serializer.jdk.secure.enabled | true | Strict whitelist mode; when false only the blacklist applies (not recommended) |
dawdler.serializer.jdk.whitelist.packages | see 5.2 | Appends whitelisted package prefixes, comma-separated, effective only in strict mode |
dawdler.serializer.jdk.blacklist.classes | see 5.1 | Appends blacklisted class names, comma-separated, always on |
dawdler.serializer.jdk.max.depth | 256 | Maximum nesting depth |
dawdler.serializer.jdk.max.array.length | 10000000 | Maximum declared length of a single array |
dawdler.serializer.jdk.max.refs | 1000000 | Maximum total references |
An empty numeric property uses its default value; a numeric value not greater than 0 throws IllegalArgumentException.
6. Pre-registering high-frequency classes with Kryo (KryoClassRegistrar)
For unregistered classes Kryo writes the full class name into every message. After pre-registration only the 1-byte registration id is written.
Classes already registered by the framework:
| Registration id | Class | Module |
|---|---|---|
| 10 | club.dawdler.core.bean.RequestBean | dawdler-core |
| 11 | club.dawdler.core.bean.ResponseBean | dawdler-core |
| 12 | club.dawdler.core.exception.RpcRemoteException | dawdler-core |
| 20 | club.dawdler.core.result.BaseResult | dawdler-load-bean |
| 21 | club.dawdler.core.result.PageResult | dawdler-load-bean |
| 22 | club.dawdler.serverplug.bean.XmlBean | dawdler-load-bean |
| 23 | club.dawdler.serverplug.load.bean.Page | dawdler-load-bean |
| 24 | club.dawdler.serverplug.load.bean.RemoteFiles | dawdler-load-bean |
| 25 | club.dawdler.serverplug.load.bean.RemoteFiles$RemoteFile | dawdler-load-bean |
6.1 Registration by business code
Implement the club.dawdler.serializer.KryoClassRegistrar interface and call kryo.register(<class>.class, id) in register(Kryo kryo).
Id allocation convention: 10-99 are reserved for the framework (10-19 for dawdler-core, 20-29 for dawdler-load-bean); business code uses 100-999999; the range from 1000000 is reserved for dynamic registration (see the dawdler-kryo-optimization README). Ids must be globally unique and must not be changed or reused after release.
Register the same way as SPI: create a club.dawdler.serializer.KryoClassRegistrar file under resources/META-INF/services; for JPMS deployment declare provides in module-info.
6.2 Compatibility
Registration changes the on-wire serialization format (full class name becomes an id), so Kryo messages are incompatible while old and new versions are deployed side by side; client and server must be upgraded together. JDK serialization is unaffected.
7. Kryo instance pool reuse
Kryo instances are pooled by the thread context class loader (TCCL): each class loader has a fixed-size striped pool (2x CPU rounded up to a power of two):
- The stripe is chosen by the low bits of the threadId modulo the stripe count; on borrow idle stripes are scanned first, and if all are busy the thread blocks and waits
- Total instances = number of active class loaders x number of stripes; within one deploy they are reused across requests and threads
Why keying by class loader helps: when multiple deploys share a worker thread pool, the TCCL switches; invalidating by thread would cause frequent Kryo instance rebuilds. With per-loader pools the same deploy always hits the same pool, and during hot deployment class resolution caches never leak into classes loaded by another loader. On deploy unload the instance pool is evicted by key, so metaspace does not leak.
Note: Kryo instances must not be used nested; do not call KryoSerializer's serialize/deserialize again inside a custom serializer.
7.1 Output buffer retention limit (outputRetainLimit)
Each stripe's UnsafeOutput starts at 2KB, doubles on demand and is not shrunk by reset(). Without a limit, after serializing an oversized message the buffer would stay at its high-water mark forever.
The current policy is to discard on overrun: after a single serialization exceeds the threshold the buffer is dropped and replaced with a fresh 2KB one, so the next large serialization needs to grow again.
-Ddawdler.serializer.kryo.outputRetainLimit=65536
- Defaults to 65536 (64KB); a custom value below 2048 takes effect as 2048
- Does not affect the on-wire serialization format; the two sides can tune it independently
- For ordinary RPC the default is fine; if large messages are the norm (batch exports, etc.), raise it to the typical message size upper bound (e.g. 1048576) so the buffer does not have to grow every time
8. Direct read/write of the payload form (SerializedPayload)
The Serializer SPI adds a SerializedPayload form in addition to byte[]: the serialization output can be an off-heap direct block (gather write with zero-copy direct transfer), and deserialization can read a direct view directly (Kryo zero-copy), allowing the core data plane to eliminate the three-hop copy of "object -> byte[] -> direct buffer". serializePayload/deserialize(SerializedPayload) are default methods, so third-party serializers need no changes (they automatically fall back to the byte[] path). SerializedPayload.ofHeap/borrowDirect/borrowDirectForRead are the three factory entry points, with these semantics:
ofHeap: wraps a heap array; release is a no-opborrowDirect(write side): borrows an off-heap block fromPayloadBufferPool; blocks >64K count against the pool's global byte budget (fair queueing with bounded waiting when the budget is exhausted)borrowDirectForRead(read side): borrowed blocks do not count against the pool budget; instead the core side'sInFlightFrameBudgetaccounts for them separately by block capacity (after tier rounding), avoiding double accounting
Release: release() returns the block to the pool via an idempotent CAS; discard() is used on failure paths where "the underlying write may still be in flight" (the block is not returned to the pool to prevent use-after-free; the budget is deducted by a Cleaner when the block is GC'd).
The Kryo direct read/write switch defaults to direct buffer (false falls back to the heap path):
-Ddawdler.serializer.kryo.directPayload.enabled=false
Payload buffer pool properties (global, process-level; idle memory cap: about 4x the sum of the tiers, about 7.9MB):
| Property | Default | Description |
|---|---|---|
dawdler.core.payload.pool.per.slot | 4 | Number of idle blocks per tier (tiers: 4K/16K/64K/128K/256K/512K/1M; payloads over 1M are not pooled and use exact allocation) |
dawdler.core.payload.pool.max.active.bytes | min(512MB, maxHeap/2) | Global byte budget for borrowed blocks >64K on the write side (read-side borrows are not counted here and are protected by the core's InFlightFrameBudget) |
dawdler.core.payload.pool.borrow.timeout | 30000 | Upper bound of the bounded wait when the budget is exhausted (ms); on timeout a PayloadBufferExhaustedException is thrown and mapped by the core to a write-budget-exhausted busy backoff |
Note: Kryo's Unsafe direct access to direct buffers requires the startup parameter --add-exports java.base/sun.nio.ch=ALL-UNNAMED (when missing, it automatically degrades to the non-Unsafe path with no correctness impact). Pool blocks are allocated with jdk.internal.misc.Unsafe.allocateMemory plus a reflectively constructed DirectByteBuffer(long,long) (requires --add-opens java.base/jdk.internal.misc=... --add-opens java.base/java.nio=...), and are deterministically freed immediately with freeMemory when the pool is full / capacity exceeds a tier / the idle cache is cleared; when unavailable it degrades to ByteBuffer.allocateDirect with GC/Cleaner as fallback. Discard paths such as write timeouts where "the write may still be in flight" are left to the GC.