• Stars
    star
    988
  • Rank 44,463 (Top 1.0 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created almost 7 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Light-weight, fast framework for object serialization in Java, with Android support.

badge1 badge2 badge3

Twitter Serial

δΈ­ζ–‡ζ–‡ζ‘£

Download

Grab the latest version via Gradle from Maven Central:

repositories {
  mavenCentral()
}

dependencies {
  implementation 'com.twitter.serial:serial:0.1.6'
}

Overview

Twitter Serial is a custom serialization implementation that's intended to improve performance and increase developer visibility into and control over an object's serialization.

This framework uses Serializers to explicitly define how a class should be serialized. Some of the major advantages of this approach include:

  • more efficient serialization avoiding reflection - preliminary metrics for a large object showed
    • more than 3x faster for roundtrip serialization (5x faster to serialize, 2.5x to deserialize)
    • around 5x smaller in byte array size
  • greater control over what's serialized for an object - all serialization is defined explicitly
  • better debugging capabilities (see debugging)

Basic Structure

To serialize an object to a byte array, use:

final Serial serial = new ByteBufferSerial();
final byte[] serializedData = serial.toByteArray(object, ExampleObject.SERIALIZER)

To deserialize from a byte array back to an object, use:

final ExampleObject object = serial.fromByteArray(ExampleObject.SERIALIZER)

Defining Serializers

  • Instead of implementing Serializable, define a serializer for every object that needs to be serialized
  • Serializers explicitly write and read each field of the object by using read/write for primitives or recursively calling serializers for other objects
  • Serializers handle null objects for you, as does read/writeString; primitive read/write methods do not
  • Serializers are stateless, so they are written as static inner classes of the object and accessed as a static instance variable SERIALIZER

For most classes, you can create a subclass of ObjectSerializer and implement serializeObject and deserializeObject

public static class ExampleObject {
    public static final ObjectSerializer<ExampleObject> SERIALIZER = new ExampleObjectSerializer();

    public final int num;
    public final SubObject obj;

    public ExampleObject(int num, @NotNull SubObject obj) {
        this.num = num;
        this.obj = obj;
    }

    ...

    private static final class ExampleObjectSerializer extends ObjectSerializer<ExampleObject> {
        @Override
        protected void serializeObject(@NotNull SerializationContext context, @NotNull SerializerOutput output,
                @NotNull ExampleObject object) throws IOException {
            output
                .writeInt(object.num) // first field
                .writeObject(object.obj, SubObject.SERIALIZER); // second field
        }

        @Override
        @NotNull
        protected ExampleObject deserializeObject(@NotNull SerializationContext context, @NotNull SerializerInput input,
                int versionNumber) throws IOException, ClassNotFoundException {
            final int num = input.readInt(); // first field
            final SubObject obj = input.readObject(SubObject.SERIALIZER); // second field
            return new ExampleObject(num, obj);
        }
    }
}

For classes that are constructed using builders, or have optional fields added (see updating-serializers), you can use a BuilderSerializer, in which you implement the methods createBuilder (which just returns a new builder object for that class) and deserializeToBuilder (where you populate the builder with the deserialized fields)

public static class ExampleObject {
    ...

    public ExampleObject(@NotNull Builder builder) {
        this.num = builder.mNum;
        this.obj = builder.mObj;
    }

    ...

    public static class Builder extends ModelBuilder<ExampleObject> {
        ...
    }

    private static final class ExampleObjectSerializer extends BuilderSerializer<ExampleObject, Builder> {
        @Override
        @NotNull
        protected Builder createBuilder() {
            return new Builder();
        }

        @Override
        protected void serializeObject(@NotNull SerializationContext context, @NotNull SerializerOutput output,
                @NotNull ExampleObject object) throws IOException {
            output.writeInt(object.num)
                .writeObject(object.obj, SubObject.SERIALIZER);
        }

         @Override
        protected void deserializeToBuilder(@NotNull SerializationContext context, @NotNull SerializerInput input,
                @NotNull Builder builder, int versionNumber) throws IOException, ClassNotFoundException {
            builder.setNum(input.readInt())
                .setObj(input.readObject(SubObject.SERIALIZER));
        }
    }
}

Serialization Utility Methods

  • CoreSerializers and CollectionSerializers contain serializers for boxed primitives and have helper methods to serialize objects like collections, enums and comparators.

    • For example, to serialize a list of Strings, you can use:

      CollectionSerializers.getListSerializer(Serializers.STRING);
  • In order to serialize an object as its base class, you can construct a base class serializer from the subclass's serializers using the getBaseClassSerializer in Serializers

    • For example, if you have ClassA and ClassB that both extend ClassC, and you want to serialize the objects as ClassC objects, you can create a serializer in ClassC using the serializers of the subclasses:

      final Serializer<ClassC> SERIALIZER = Serializers.getBaseClassSerializer(
          SerializableClass.create(ClassA.class, new ClassA.ClassASerializer()),
          SerializableClass.create(ClassB.class, new ClassB.ClassBSerializer()));

    Note

    You must create new instances of ClassA and B serializers rather than using the static object defined in those classes. Since ClassC is initialized as part of its subclasses, using static objects of its subclasses in its initialization will create a cyclic dependency that will likely lead to a cryptic NPE.

Updating Serializers

If you add or remove a field for an object that's being stored as serialized data, there are a few ways to handle it:

OptionalFieldException

If you add a field to the end of an object, your new serializer will reach the end of an old object when trying to read the new field, which will cause it to throw an OptionalFieldException.

BuilderSerializer handles OptionalFieldExceptions for you by just ignoring that field in the builder, stopping deserialization, and building the rest of the object as is. If you're using a regular Serializer instead, you can explicitly catch the OptionalFieldException and set the remaining field(s) to default values as appropriate.

  • Say, for example, you wanted to add a String 'name' to the end of the ExampleObject above

    • For both serializer types, you could simply add .writeString(obj.name) to serializeObject

    • For the BuilderSerializer, to deserialize you would add .setName(input.readString()) to the end of deserializeToBuilder. In the case where an older object without the name field is being deserialized, an OptionalFieldException would be thrown and caught when reading the String, causing the object to be built as is without the name field explicitly set.

    • For the regular Serializer, you would change deserializeObject as follows:

      @Override
      @NotNull
      protected ExampleObject deserializeObject(@NotNull SerializationContext context, @NotNull SerializerInput input,
              int versionNumber) throws IOException, ClassNotFoundException {
          final int num = input.readInt();
          final SubObject obj = input.readObject(SubObject.SERIALIZER);
          final String name;
          try {
              name = input.readString();
          } catch (OptionalFieldException e) {
              name = DEFAULT_NAME;
          }
          return new ExampleObject(num, obj, name);
      }

Version numbers

Another option is to increase the version number of the serializer, and define the deserialization behavior for older versions. To do this, pass the version number into the constructor of the SERIALIZER object, and then in the deserialize method you can specify what to do differently for previous versions.

  • To change the above example to use version numbers, do the following:

    final Serializer<ExampleObject> SERIALIZER = new ExampleObjectSerializer(1);
    ...
    
    @Override
    @NotNull
    protected ExampleObject deserializeObject(@NotNull SerializationContext context, @NotNull SerializerInput input, int versionNumber)
            throws IOException, ClassNotFoundException {
        final int num = input.readInt();
        final SubObject obj = input.readObject(SubObject.SERIALIZER);
        final String name;
        if (versionNumber < 1) {
            name = DEFAULT_NAME;
        } else {
            name = input.readString();
        }
        return new ExampleObject(num, obj, name);
    }

If you remove a field from the middle of an object, you need to ignore the whole object during deserialization by using the skipObject method in SerializationUtils. This way you don't need to keep the serializer if you are removing the object all together.

  • Say in the above example you also wanted to remove the obj field and delete SubObject:

    @Override
    @NotNull
    protected ExampleObject deserializeObject(@NotNull SerializationContext context, @NotNull SerializerInput input, int versionNumber)
            throws IOException, ClassNotFoundException {
        final int num = input.readInt();
        if (versionNumber < 1) {
            SerializationUtils.skipObject()
            name = DEFAULT_NAME;
        } else {
            name = input.readString();
        }
        return new ExampleObject(num, name);
    }

Another option is to call input.peekType(), which allows you to check the type of the next field before reading the object. This is especially helpful if you hadn't updated the version before making a change and don't want to wipe the database, since it allows you to differentiate between the two versions without a version number. Note that this only works if the two types are different.

@Override
@NotNull
protected ExampleObject deserializeObject(@NotNull SerializationContext context, @NotNull SerializerInput input, int versionNumber)
        throws IOException, ClassNotFoundException {
    final int num = input.readInt();
    if (input.peekType() == SerializerDefs.TYPE_START_OBJECT) {
        SerializationUtils.skipObject();
        name = DEFAULT_NAME;
    } else {
        name = input.readString();
    }
    return new ExampleObject(num, name);
}

Value Serializers

Some objects are so simple that do not require support for versioning: Integer, String, Size, Rect... Using an ObjectSerializer with these objects adds an envelope of 2-3 bytes around the serialized data, which can add significant overhead. When versioning is not required, ValueSerializer is a better choice:

public static final Serializer<Boolean> BOOLEAN = new ValueSerializer<Boolean>() {
    @Override
    protected void serializeValue(@NotNull SerializationContext context, @NotNull SerializerOutput output, @NotNull Boolean object) throws IOException {
        output.writeBoolean(object);
    }

    @NotNull
    @Override
    protected Boolean deserializeValue(@NotNull SerializationContext context, @NotNull SerializerInput input) throws IOException {
        return input.readBoolean();
    }
};

This is just a simpler version of ObjectSerializer that handles null, otherwise, just writes the values into the stream.

Note

ValueSerializer writes null to the stream when given a null value. As a result, the first field written into the stream by serializeValue can't be null, since it would be ambiguous. ValueSerializer detects this as an error and throws an exception.

Caution!

Value serializers should only be used when their format is known to be fixed, since they do not support any form of backwards compatibility.

Debugging

serial also contains methods to help with debugging:

  • dumpSerializedData will create a string log of the data in the serialized byte array
  • validateSerializedData ensures that the serialized object has a valid structure (e.g. every object start header has a matching end header)

Exceptions now contain more information about the serialization failure, specifically information about the expected type to be deserialized and the type that was found, based on headers written for each value.

More Repositories

1

the-algorithm

Source code for Twitter's Recommendation Algorithm
Scala
60,968
star
2

twemoji

Emoji for everyone. https://twemoji.twitter.com/
HTML
16,575
star
3

typeahead.js

typeahead.js is a fast and fully-featured autocomplete library
JavaScript
16,526
star
4

twemproxy

A fast, light-weight proxy for memcached and redis
C
12,000
star
5

the-algorithm-ml

Source code for Twitter's Recommendation Algorithm
Python
9,844
star
6

finagle

A fault tolerant, protocol-agnostic RPC system
Scala
8,742
star
7

hogan.js

A compiler for the Mustache templating language
JavaScript
5,143
star
8

labella.js

Placing labels on a timeline without overlap.
JavaScript
3,869
star
9

scala_school

Lessons in the Fundamentals of Scala
HTML
3,700
star
10

AnomalyDetection

Anomaly Detection with R
R
3,529
star
11

scalding

A Scala API for Cascading
Scala
3,467
star
12

twitter-text

Twitter Text Libraries. This code is used at Twitter to tokenize and parse text to meet the expectations for what can be used on the platform.
HTML
3,051
star
13

TwitterTextEditor

A standalone, flexible API that provides a full-featured rich text editor for iOS applications.
Swift
2,950
star
14

opensource-website

Twitter's open source website, identifying projects we've released, organizations we support, and the work we do to support open source.
SCSS
2,918
star
15

util

Wonderful reusable code from Twitter
Scala
2,679
star
16

algebird

Abstract Algebra for Scala
Scala
2,288
star
17

finatra

Fast, testable, Scala services built on TwitterServer and Finagle
Scala
2,271
star
18

effectivescala

Twitter's Effective Scala Guide
HTML
2,241
star
19

summingbird

Streaming MapReduce with Scalding and Storm
Scala
2,136
star
20

pelikan

Pelikan is Twitter's unified cache backend
C
1,921
star
21

ios-twitter-image-pipeline

Twitter Image Pipeline is a robust and performant image loading and caching framework for iOS clients
C
1,851
star
22

twurl

OAuth-enabled curl for the Twitter API
Ruby
1,790
star
23

twitter-server

Twitter-Server defines a template from which services at Twitter are built
Scala
1,542
star
24

rezolus

Systems performance telemetry
Rust
1,541
star
25

activerecord-reputation-system

An Active Record Reputation System for Rails
Ruby
1,334
star
26

communitynotes

Documentation and source code powering Twitter's Community Notes
Python
1,319
star
27

compose-rules

Static checks to aid with a healthy adoption of Compose
Kotlin
1,311
star
28

fatcache

Memcache on SSD
C
1,301
star
29

rsc

Experimental Scala compiler focused on compilation speed
Scala
1,245
star
30

elephant-bird

Twitter's collection of LZO and Protocol Buffer-related Hadoop, Pig, Hive, and HBase code.
Java
1,137
star
31

cassovary

Cassovary is a simple big graph processing library for the JVM
Scala
1,039
star
32

hbc

A Java HTTP client for consuming Twitter's realtime Streaming API
Java
963
star
33

twemcache

Twemcache is the Twitter Memcached
C
925
star
34

innovators-patent-agreement

Innovators Patent Agreement (IPA)
919
star
35

vireo

Vireo is a lightweight and versatile video processing library written in C++11
C++
919
star
36

twitter-korean-text

Korean tokenizer
Scala
834
star
37

scrooge

A Thrift parser/generator
Scala
785
star
38

BreakoutDetection

Breakout Detection via Robust E-Statistics
C++
753
star
39

GraphJet

GraphJet is a real-time graph processing library.
Java
696
star
40

twitter-cldr-rb

Ruby implementation of the ICU (International Components for Unicode) that uses the Common Locale Data Repository to format dates, plurals, and more.
Ruby
667
star
41

bijection

Reversible conversions between types
Scala
657
star
42

chill

Scala extensions for the Kryo serialization library
Scala
607
star
43

ios-twitter-network-layer

Twitter Network Layer is a scalable and feature rich network layer built on top of NSURLSession for Apple platforms
Objective-C
573
star
44

hadoop-lzo

Refactored version of code.google.com/hadoop-gpl-compression for hadoop 0.20
Shell
544
star
45

storehaus

Storehaus is a library that makes it easy to work with asynchronous key value stores
Scala
464
star
46

rpc-perf

A tool for benchmarking RPC services
Rust
458
star
47

d3kit

D3Kit is a set tools to speed D3 related project development
JavaScript
429
star
48

scoot

Scoot is a distributed task runner, supporting both a proprietary API and Bazel's Remote Execution.
Go
347
star
49

twitter-cldr-js

JavaScript implementation of the ICU (International Components for Unicode) that uses the Common Locale Data Repository to format dates, plurals, and more. Based on twitter-cldr-rb.
JavaScript
345
star
50

scala_school2

Scala School 2
Scala
340
star
51

rustcommon

Common Twitter Rust lib
Rust
339
star
52

wordpress

The official Twitter plugin for WordPress. Embed Twitter content and grow your audience on Twitter.
PHP
310
star
53

ios-twitter-logging-service

Twitter Logging Service is a robust and performant logging framework for iOS clients
Objective-C
299
star
54

nodes

A library to implement asynchronous dependency graphs for services in Java
Java
246
star
55

SentenTree

A novel text visualization technique
JavaScript
226
star
56

interactive

Twitter interactive visualization
HTML
213
star
57

joauth

A Java library for authenticating HTTP Requests using OAuth
Java
211
star
58

thrift_client

A Thrift client wrapper that encapsulates some common failover behavior
Ruby
196
star
59

hpack

Header Compression for HTTP/2
Java
192
star
60

zktraffic

ZooKeeper protocol analyzer and stats gathering daemon
Python
165
star
61

twemoji-parser

A simple library for identifying emoji entities within a string in order to render them as Twemoji.
Scala
162
star
62

cache-trace

A collection of Twitter's anonymized production cache traces.
Shell
162
star
63

sbf

Java
159
star
64

tormenta

Scala extensions for Storm
Scala
132
star
65

whiskey

HTTP library for Android (beta)
Java
131
star
66

hraven

hRaven collects run time data and statistics from MapReduce jobs in an easily queryable format
Java
127
star
67

netty-http2

HTTP/2 for Netty
Java
120
star
68

sqrl

A Safe, Stateful Rules Language for Event Streams
TypeScript
100
star
69

ccommon

Cache Commons
C
99
star
70

focus

Focus aligns Git worktree content based on outlines of a repository's Bazel build graph. Focused repos are sparse, shallow, and thin and unlock markedly better performance in large repos.
Rust
91
star
71

dict_minimize

Access scipy optimizers from your favorite deep learning framework.
Python
77
star
72

metrics

76
star
73

twitter.github.io

HTML
71
star
74

go-bindata

Go
68
star
75

diffusion-rl

Python
66
star
76

birdwatch

64
star
77

cloudhopper-commons

Cloudhopper Commons
Java
57
star
78

twitter-cldr-npm

TwitterCldr npm package
JavaScript
49
star
79

.github

Twitter GitHub Organization-wide files
48
star
80

bazel-multiversion

Bazel rules to resolve, fetch and manage 3rdparty JVM dependencies with support for multiple parallel versions of the same dependency. Powered by Coursier.
Scala
47
star
81

libwatchman

A C interface to watchman
C
44
star
82

sslconfig

Twitter's OpenSSL Configuration
42
star
83

ios-twitter-apache-thrift

A thrift encoding and decoding library for Swift
Swift
41
star
84

gatekeeper-service

GateKeeper is a service built to automate the manual steps involved in onboarding, offboarding, and lost asset scenarios.
Python
36
star
85

dodo

The Twitter OSS Project Builder
Shell
35
star
86

repo-scaffolding

Tools for creating repos based on open source standards and best practices
33
star
87

iago2

A load generator, built for engineers
Scala
24
star
88

caladrius

Performance modelling system for Distributed Stream Processing Systems (DSPS) such as Apache Heron and Apache Storm
Python
22
star
89

ossdecks

Repository for Twitter Open Source Decks
10
star
90

curation-style-guide

Document Repository for Twitter's Curation Style Guide
10
star
91

analytics-infra-governance

Description of the process for how to commit, review, and release code to the Scalding OSS family (Scalding, Summingbird, Algebird, Bijection, Storehaus, etc)
9
star
92

gpl-commitment

Twitter's GPL Cooperation Commitment
5
star
93

second-control-probability-distributions

4
star
94

google-tag-manager-event-tag

Smarty
3
star
95

google-tag-manager-base-tag

Smarty
2
star