sanity
sanity

Reputation: 35772

Lightweight way to persist objects in Java

I'm trying to design a lightweight way to store persistent data in Java. I've already got a very efficient way to serialize POJOs to DataOutputStreams (and back), but I'm trying to think of a good way to ensure that changes to the data in the POJOs gets serialized when necessary.

This is for a client-side app where I'm trying to keep the size of the eventual distributable as low as possible, so I'm reluctant to use anything that would pull-in heavy-weight dependencies. Right now my distributable is almost 10MB, and I don't want it to get much bigger.

I've considered DB4O but its too heavy - I need something light. Really its probably more a design pattern I need, rather than a library.

Any ideas?

Upvotes: 2

Views: 246

Answers (2)

mikera
mikera

Reputation: 106351

If you already have a compact data output format in bytes (which I assume you have if you can persist efficiently to a DataOutputStream) then an efficient and general technique is to use run-length-encoding on the difference between the previous byte array output and the new byte array output.

Points to note:

  • If the object has not changed, the difference in byte arrays will be an array of zeros and hence will compress very small....
  • For the first time you serialize the object, consider the previous output to be all zeros so that you communicate a complete set of data
  • You probably want to be a bit clever when the object has variable-sized substructures....
  • You can also try zipping the difference rather than RLE - might be more efficient in some cases where you have a large object graph with a lot of changes

Upvotes: 0

Stefan Kendall
Stefan Kendall

Reputation: 67822

The 'lightest weight' persistence option will almost surely be simply marking some classes Serializable and reading/writing from some fixed location. Are you trying to accomplish something more complex than this? If so, it's time to bundle hsqldb and use an ORM.

If your users are tech savvy, or you're just worried about initial payload, there are libraries which can pull dependencies at runtime, such as Grape.

Upvotes: 1

Related Questions