[id='data_encoding']
= Data Encoding
Encoding is the data conversion operation done by {brandname} caches before storing data, and when reading back from storage.

== Overview
Encoding allows dealing with a certain data format during API calls (map, listeners, stream, etc) while the format effectively stored
is different.

The data conversions are handled by instances of _org.infinispan.commons.dataconversion.Encoder_ :

[source,java]
----
include::code_examples/Encoder.java[]
----

== Default encoders

{brandname} automatically picks the Encoder depending on the cache configuration. The table below shows which internal Encoder is used for several configurations:

[options="header",cols="4"]
|===
| Mode | Configuration | Encoder | Description
| Embedded/Server
| Default
| IdentityEncoder
| Passthrough encoder, no conversion done

| Embedded
| StorageType.OFF_HEAP
| GlobalMarshallerEncoder
| Use the {brandname} internal marshaller to convert to byte[]. May delegate to the configured marshaller in the cache manager.

| Embedded
| StorageType.BINARY
| BinaryEncoder
| Use the {brandname} internal marshaller to convert to byte[], except for primitives and String.

| Server
| StorageType.OFF_HEAP
| IdentityEncoder
| Store byte[]s directly as received by remote clients
|===

== Overriding programmatically

It is possible to override programmatically the encoding used for both keys and values, by calling the _.withEncoding()_ method variants from _AdvancedCache_.

Example, consider the following cache configured as OFF_HEAP:

[source,java]
----
include::code_examples/EncoderOverride.java[]
----

The override can be useful if any operation in the cache does not require decoding, such as counting number of entries,
or calculating the size of byte[] of an OFF_HEAP cache.

== Defining Custom Encoders

A custom encoder can be registered in the _EncoderRegistry_.

CAUTION: Ensure that the registration is done in every node of the cluster, before starting the caches.

Consider a custom encoder used to compress/decompress with gzip:

[source,java]
----
include::code_examples/EncoderCustomGzip.java[]
----

It can be registered by:

[source,java]
----
include::code_examples/EncoderCustomGzipRegister.java[]
----

And then be used to write and read data from a cache:

[source,java]
----
include::code_examples/EncoderCustomExample.java[]
----
