|
24 | 24 | import org.msgpack.core.MessageUnpacker; |
25 | 25 | import org.msgpack.core.buffer.ArrayBufferInput; |
26 | 26 |
|
| 27 | +import java.io.ByteArrayOutputStream; |
27 | 28 | import java.io.File; |
28 | 29 | import java.io.FileInputStream; |
29 | 30 | import java.io.FileOutputStream; |
|
36 | 37 | import java.util.HashMap; |
37 | 38 | import java.util.List; |
38 | 39 | 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; |
39 | 45 |
|
40 | 46 | import static org.junit.Assert.assertArrayEquals; |
41 | 47 | import static org.junit.Assert.assertEquals; |
@@ -379,4 +385,54 @@ public void testWritePrimitiveObjectViaObjectMapper() |
379 | 385 | assertEquals(4, unpacker.unpackInt()); |
380 | 386 | assertEquals(5, unpacker.unpackLong()); |
381 | 387 | } |
| 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 | + } |
382 | 438 | } |
0 commit comments