The database instances are not thread-safe, so each thread needs a own instance. All the database instances will share the same connection to the storage for the same URL. For more information look at Java Multi threads and databases.
Java WebApp runs inside a Servlet container with a pool of threads that work the requests.
There are mainly 2 solutions:
package com.orientechnologies.test;
import javax.servlet.*;
public class Example extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
ODatabaseDocument database = ODatabaseDocumentPool.global().acquire("local:/temp/db", "admin", "admin");
try {
// USER CODE
} finally {
database.close();
}
}
}
Servlets are the best way to automatise database control inside WebApps. The trick is to create a Filter that get a database from the pool and binds it in current ThreadLocal before to execute the Servlet code. Once returned the ThreadLocal is cleared and database released to the pool.
In this example a new database instance is created per request, opened and at the end closed.
package com.orientechnologies.test;
import javax.servlet.*;
public class OrientDBFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) {
ODatabaseDocument database = new ODatabaseDocumentTx("local:/temp/db").open("admin", "admin");
try{
chain.doFilter(request, response);
} finally {
database.close();
}
}
}
In this example the database pool is used.
package com.orientechnologies.test;
import javax.servlet.*;
public class OrientDBFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) {
ODatabaseDocument database = ODatabaseDocumentPool.global().acquire("local:/temp/db", "admin", "admin");
try{
chain.doFilter(request, response);
} finally {
database.close();
}
}
public void destroy() {
ODatabaseDocumentPool.global().close();
}
}
Now we've create the filter class it needs to be registered in the web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<filter>
<filter-name>OrientDB</filter-name>
<filter-class>com.orientechnologies.test.OrientDBFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OrientDB</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>