01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (license2)
04: * Initial Developer: H2 Group
05: */
06: package org.h2.test.db;
07:
08: import java.sql.Connection;
09: import java.sql.PreparedStatement;
10: import java.sql.ResultSet;
11: import java.sql.Statement;
12: import java.util.Random;
13:
14: import org.h2.test.TestAll;
15: import org.h2.test.TestBase;
16:
17: /**
18: * Multi-threaded tests.
19: */
20: public class TestMultiThread extends TestBase implements Runnable {
21:
22: private boolean stop;
23: private TestMultiThread parent;
24: private Random random;
25: private Connection conn;
26: private Statement stat;
27:
28: public TestMultiThread() {
29: }
30:
31: private TestMultiThread(TestAll config, TestMultiThread parent)
32: throws Exception {
33: this .config = config;
34: this .parent = parent;
35: random = new Random();
36: conn = getConnection();
37: stat = conn.createStatement();
38: }
39:
40: public void test() throws Exception {
41:
42: Connection conn = getConnection();
43: Statement stat = conn.createStatement();
44: stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)");
45: int len = getSize(10, 200);
46: Thread[] threads = new Thread[len];
47: for (int i = 0; i < len; i++) {
48: threads[i] = new Thread(new TestMultiThread(config, this ));
49: }
50: for (int i = 0; i < len; i++) {
51: threads[i].start();
52: }
53: int sleep = getSize(400, 10000);
54: Thread.sleep(sleep);
55: this .stop = true;
56: for (int i = 0; i < len; i++) {
57: threads[i].join();
58: }
59: ResultSet rs = stat.executeQuery("SELECT COUNT(*) FROM TEST");
60: rs.next();
61: trace("max id=" + rs.getInt(1));
62: conn.close();
63: }
64:
65: Connection getConnection() throws Exception {
66: return getConnection("jdbc:h2:mem:multiThread");
67: }
68:
69: public void run() {
70: try {
71: while (!parent.stop) {
72: stat.execute("SELECT COUNT(*) FROM TEST");
73: stat.execute("INSERT INTO TEST VALUES(NULL, 'Hi')");
74: PreparedStatement prep = conn
75: .prepareStatement("UPDATE TEST SET NAME='Hello' WHERE ID=?");
76: prep.setInt(1, random.nextInt(10000));
77: prep.execute();
78: prep = conn
79: .prepareStatement("SELECT * FROM TEST WHERE ID=?");
80: prep.setInt(1, random.nextInt(10000));
81: ResultSet rs = prep.executeQuery();
82: while (rs.next()) {
83: rs.getString("NAME");
84: }
85: }
86: conn.close();
87: } catch (Exception e) {
88: logError("multi", e);
89: }
90: }
91:
92: }
|