Search code examples
javaneo4jplayframeworkconnection-poolingautocloseable

Neo4j Driver in play


I use a Neo4j java driver in my play app.

Currently I initialize a new driver for every controller (ie. for every http call). When the autoclosable close method runs it seems to block the entire call for about almost two seconds. Running without closing the drivers (obviously a bad idea) cuts my tests down from 25 seconds to 5.

I do suspect I use the driver in the wrong way and I guess I should be using one driver application wide but cannot figure out how. What is the correct way to use the java Neo4j driver in the play framework?


Solution

  • The Javadoc for the Driver interface states:

    Driver implementations are typically thread-safe, act as a template for Session creation and host a connection pool. All configuration and authentication settings are held immutably by the Driver. Should different settings be required, a new Driver instance should be created.

    A driver maintains a connection pool for each remote Neo4j server. Therefore the most efficient way to make use of a Driver is to use the same instance across the application.

    So, generally, you should use a single Driver instance.

    One way to share the same instance is to implement a factory class that provides a singleton Driver instance. Here is a very basic thread-safe example:

    class DriverFactory {
        private static Driver instance;
        public static synchronized Driver getDriver() {
            if (instance == null) {
                instance = GraphDatabase.driver(...);
            }
            return instance;
        }
    }