1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.jxpath.ri;
17
18 import junit.framework.TestCase;
19
20 import org.apache.commons.jxpath.JXPathContext;
21
22 /***
23 * Test thread safety.
24 *
25 * @author Dmitri Plotnikov
26 * @version $Revision: 1.3 $ $Date: 2004/02/29 14:17:44 $
27 */
28
29 public class StressTest extends TestCase {
30
31 private static final int THREAD_COUNT = 50;
32 private static final int THREAD_DURATION = 1000;
33 private static JXPathContext context;
34 private static int count;
35 private static Throwable exception;
36
37 /***
38 * Construct a new instance of this test case.
39 *
40 * @param name Name of the test case
41 */
42 public StressTest(String name) {
43 super(name);
44 }
45
46 public void testThreads() throws Throwable {
47 context = JXPathContext.newContext(null, new Double(100));
48 Thread[] threadArray = new Thread[THREAD_COUNT];
49 for (int i = 0; i < THREAD_COUNT; i++) {
50 threadArray[i] = new Thread(new StressRunnable());
51 }
52
53 for (int i = 0; i < threadArray.length; i++) {
54 threadArray[i].start();
55 }
56
57 for (int i = 0; i < threadArray.length; i++) {
58 try {
59 threadArray[i].join();
60 }
61 catch (InterruptedException e) {
62 assertTrue("Interrupted", false);
63 }
64 }
65
66 if (exception != null) {
67 throw exception;
68 }
69 assertEquals("Test count", THREAD_COUNT * THREAD_DURATION, count);
70 }
71
72 private final class StressRunnable implements Runnable {
73 public void run() {
74 for (int j = 0; j < THREAD_DURATION && exception == null; j++) {
75 try {
76 double random = 1 + Math.random();
77 double sum =
78 ((Double) context.getValue("/ + " + random))
79 .doubleValue();
80 assertEquals(100 + random, sum, 0.0001);
81 synchronized (context) {
82 count++;
83 }
84 }
85 catch (Throwable t) {
86 exception = t;
87 }
88 }
89 }
90 }
91 }