Java

Share an h2 in-memory database among several JVMs

I hate when things are written in the docs but not clearly enough to understand it on the first time.

I wish I were the only one not to have get this right at first, but if you look in google for terms like

“share h2 database among applications”

“common h2 database among jvms”

“accessing in-memory database from another jvm”

you’ll find plenty of confused people too.

SO here is the explanation

Because you are writing some test or POC, you want to use an In-Memory Database.

H2 is cool, you can look at the tutorial and cook-up a config pretty fast and it works very well.

Then let’s say you want to share your database amongst different processes/JVMs. That’s when the documentation becomes unclear (although everything is explained there).

the first process is going to create the DB, with the following URL :

"jdbc:h2:mem:db1"

and it’s going to need to start a tcp Server

final String[] args = new String[] {
"-tcpPort", "8092",
"-tcpAllowOthers","true" };

org.h2.tools.Server server = org.h2.tools.Server.createTcpServer(args).start();

Of course do not forget to stop the server when you exit the application

server.stop();

The other processes can then access your DB by using the following URL:

"jdbc:h2:tcp://localhost:8092/mem:db1"

That’s it.

6 thoughts on “Share an h2 in-memory database among several JVMs”

    1. This code works perfect, had to make changes to config file in Spring to create the tcp connection when db was created for first time. Was able to access it on 8092 port. Thanks a lot !!!!!!!

  1. It would be greate, if we could include the options to start the tcp server directly in the connection string. Isn’t this possible? [i.e. something like jdbc:h2:mem:db1;TCP_PORT=8092;TCP_ALLOW_OTHERS=true]

  2. I have spring boot application running on 4 nodes how can I implement H2 database to share across 4 nodes. Can you please help me with this?

Leave a comment