@Test
public void testMultiProcess() throws Exception {
// create and start a hsql server, a stand-alone (memory backed) db
// (important: a stand-alone server should be used because simple
// file based access i.e. jdbc:hsqldb:file is NOT process-safe.)
Server server = new Server();
server.setDaemon(true);
server.setSilent(true); // disables LOTS of trace
final String className = getClass().getName();
String dbName = "test";
server.setDatabasePath(0, "mem:"+dbName);
server.setDatabaseName(0, dbName);
server.start();
//create the store so that the tests can start right away
StorageUtils.createWebStore(conf, String.class, WebPage.class);
// create a fixed thread pool
int numThreads = 4;
ExecutorService pool = Executors.newFixedThreadPool(numThreads);
// spawn multiple processes, each thread spawns own process
Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
for (int i = 0; i < numThreads; i++) {
tasks.add(new Callable<Integer>() {
@Override
public Integer call() {
try {
String separator = System.getProperty("file.separator");
String classpath = System.getProperty("java.class.path");
String pathSeparator = System.getProperty("path.separator");
// connect local sql service
classpath = "./src/testprocess" + pathSeparator + classpath;
String path = System.getProperty("java.home") + separator + "bin"
+ separator + "java";
ProcessBuilder processBuilder = new ProcessBuilder(path, "-cp",
classpath, className);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
InputStream in = process.getInputStream();
int exit = process.waitFor();
//print the output of the process
System.out.println("===Process stream for " + Thread.currentThread()
+ "\n" + IOUtils.toString(in) + "===End of process stream.");
in.close();
// process should exit with zero code
return exit;
} catch (Exception e) {
e.printStackTrace();
// this will fail the test
return 1;
}
}
});
}
// submit them at once
List<Future<Integer>> results = pool.invokeAll(tasks);
// check results
for (Future<Integer> result : results) {
assertEquals(0, (int) result.get());
}
//stop db
server.stop();
}