I have a Spring service, and I want to test its correctness for concurrent thread.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class SerialNumberServiceTest {
@Autowired
private SerialNumberService service;
private final static int NUM_THREADS = 10;
private final static int NUM_ITERATIONS = 100;
@Test
public void testSynchronized(){
ExecutorService executor = Executors.newFixedThreadPool(10);
final Set<String> result = new HashSet<String>();
int size = 0;
for(int i = 0; i < NUM_THREADS; i++){
executor.submit(new Runnable() {
@Override
public void run() {
for (int j = 0; j < NUM_ITERATIONS; j++) {
String code = service.generateSerialNumberByModelCode("LP");
result.add(code);
}
}
});
}
assertEquals(NUM_ITERATIONS * NUM_THREADS, result.size());
}
}
I want assert how many codes was generated and check whether there is duplicate code. But the result Set is empty. I do not know why.
On the other hand, if I try to update values of the service instance in the threads, I also find the values are not saved. e.g.
public void run() {
for (int j = 0; j < NUM_ITERATIONS; j++) {
String code = service.generateSerialNumberByModelCode("LP");
service.incrValue();
result.add(code);
}
}
And at last, service.getValue() is non-changed.
Anyone can explain this for me?