My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package eg.jconch.testing;

import jconch.testing.SerialExecutorService;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* Example usage of the {@link jconch.testing.SerialExecutorService}.
*/
public class SerialExecutorServiceExample {

@Test
public void testSerialExecutionWorks() {

final ExecutorService executor = new SerialExecutorService();
final ClassThatSpawnsWork worker = new ClassThatSpawnsWork(executor);
worker.multiplyService(25, 4);
assertEquals(100, worker.lastResult[0].intValue());
}

@Test(expectedExceptions = NullPointerException.class)
public void testThreadedExecutionBroken() {

final ExecutorService executor = Executors.newSingleThreadExecutor();
final ClassThatSpawnsWork worker = new ClassThatSpawnsWork(executor);
worker.multiplyService(25, 4);
assertEquals(100, worker.lastResult[0].intValue());
}

/**
* A simple class that spawns work asynchronously. Not production code by any means.
*/
private static class ClassThatSpawnsWork {

private final ExecutorService executor;
private Integer[] lastResult = new Integer[1];

public ClassThatSpawnsWork(ExecutorService executor) {
this.executor = executor;
}

void multiplyService(final int factor1, final int factor2) {
executor.submit(new Callable<Void>(){
public Void call() throws Exception {
Thread.sleep(1000); //lengthy computation
lastResult[0] = factor1 * factor2;
return null;
}
});
}
}
}

Change log

r126 by HamletDRC on Jan 15, 2009   Diff
Added a SerialExecutorService, unit tests,
and an example usage.

This ExecutorService is designed to be
used with unit testing. It is nice to
force single threaded behavior on an
object that normally has a thread pool.

The unit tests are mediocre. Exceptions
are not tested, and some test methods test
several things at once.
Go to: 
Project members, sign in to write a code review

Older revisions

All revisions of this file

File info

Size: 1670 bytes, 56 lines
Powered by Google Project Hosting