Skip to content

Commit 863a3f2

Browse files
committed
Merge pull request #315 from msgpack/add_concurrent_test
Add concurrent serialization test in MessagePackGeneratorTest
2 parents 5e130a9 + 28be745 commit 863a3f2

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

msgpack-jackson/src/test/java/org/msgpack/jackson/dataformat/MessagePackGeneratorTest.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import org.msgpack.core.MessageUnpacker;
2525
import org.msgpack.core.buffer.ArrayBufferInput;
2626

27+
import java.io.ByteArrayOutputStream;
2728
import java.io.File;
2829
import java.io.FileInputStream;
2930
import java.io.FileOutputStream;
@@ -36,6 +37,11 @@
3637
import java.util.HashMap;
3738
import java.util.List;
3839
import java.util.Map;
40+
import java.util.concurrent.Callable;
41+
import java.util.concurrent.ExecutorService;
42+
import java.util.concurrent.Executors;
43+
import java.util.concurrent.Future;
44+
import java.util.concurrent.TimeUnit;
3945

4046
import static org.junit.Assert.assertArrayEquals;
4147
import static org.junit.Assert.assertEquals;
@@ -379,4 +385,54 @@ public void testWritePrimitiveObjectViaObjectMapper()
379385
assertEquals(4, unpacker.unpackInt());
380386
assertEquals(5, unpacker.unpackLong());
381387
}
388+
389+
@Test
390+
public void testInMultiThreads()
391+
throws Exception
392+
{
393+
int threadCount = 8;
394+
final int loopCount = 4000;
395+
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
396+
final ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
397+
objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
398+
final List<ByteArrayOutputStream> buffers = new ArrayList<ByteArrayOutputStream>(threadCount);
399+
List<Future<Exception>> results = new ArrayList<Future<Exception>>();
400+
401+
for (int ti = 0; ti < threadCount; ti++) {
402+
buffers.add(new ByteArrayOutputStream());
403+
final int threadIndex = ti;
404+
results.add(executorService.submit(new Callable<Exception>()
405+
{
406+
@Override
407+
public Exception call()
408+
throws Exception
409+
{
410+
try {
411+
for (int i = 0; i < loopCount; i++) {
412+
objectMapper.writeValue(buffers.get(threadIndex), threadIndex);
413+
}
414+
return null;
415+
}
416+
catch (IOException e) {
417+
return e;
418+
}
419+
}
420+
}));
421+
}
422+
423+
for (int ti = 0; ti < threadCount; ti++) {
424+
Future<Exception> exceptionFuture = results.get(ti);
425+
Exception exception = exceptionFuture.get(20, TimeUnit.SECONDS);
426+
if (exception != null) {
427+
throw exception;
428+
}
429+
else {
430+
ByteArrayOutputStream outputStream = buffers.get(ti);
431+
MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(outputStream.toByteArray());
432+
for (int i = 0; i < loopCount; i++) {
433+
assertEquals(ti, unpacker.unpackInt());
434+
}
435+
}
436+
}
437+
}
382438
}

0 commit comments

Comments
 (0)