|
| 1 | +/** |
| 2 | + * Copyright 2009-2019 the original author or authors. |
| 3 | + * <p> |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * <p> |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * <p> |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.apache.ibatis.submitted.typehandlerregistry_race_condition; |
| 17 | + |
| 18 | +import org.apache.ibatis.type.JdbcType; |
| 19 | +import org.apache.ibatis.type.TypeHandlerRegistry; |
| 20 | +import org.junit.jupiter.api.AfterEach; |
| 21 | +import org.junit.jupiter.api.BeforeEach; |
| 22 | +import org.junit.jupiter.api.Test; |
| 23 | +import org.testcontainers.shaded.com.google.common.util.concurrent.Futures; |
| 24 | + |
| 25 | +import java.util.List; |
| 26 | +import java.util.concurrent.CountDownLatch; |
| 27 | +import java.util.concurrent.ExecutorService; |
| 28 | +import java.util.concurrent.Executors; |
| 29 | +import java.util.concurrent.Future; |
| 30 | +import java.util.stream.Collectors; |
| 31 | +import java.util.stream.IntStream; |
| 32 | + |
| 33 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 34 | + |
| 35 | +class TypeHandlerRegistryHasHandlerRaceConditionTest { |
| 36 | + |
| 37 | + private static final int THREAD_COUNT = 4; |
| 38 | + |
| 39 | + private ExecutorService executorService; |
| 40 | + |
| 41 | + @BeforeEach |
| 42 | + void setUp() { |
| 43 | + executorService = Executors.newFixedThreadPool(THREAD_COUNT); |
| 44 | + } |
| 45 | + |
| 46 | + @AfterEach |
| 47 | + void setDown() { |
| 48 | + executorService.shutdownNow(); |
| 49 | + } |
| 50 | + |
| 51 | + @Test |
| 52 | + void shouldAutoRegisterEnumTypeInMultiThreadEnvironment() { |
| 53 | + for (int iteration = 0; iteration < 1000; iteration++) { |
| 54 | + TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry(); |
| 55 | + CountDownLatch startLatch = new CountDownLatch(1); |
| 56 | + |
| 57 | + List<Future<Object>> taskResults = IntStream.range(0, THREAD_COUNT) |
| 58 | + .mapToObj(taskIndex -> executorService.submit(() -> { |
| 59 | + startLatch.await(); |
| 60 | + assertTrue(typeHandlerRegistry.hasTypeHandler(TestEnum.class, JdbcType.VARCHAR), |
| 61 | + "TypeHandler not registered"); |
| 62 | + return null; |
| 63 | + })).collect(Collectors.toList()); |
| 64 | + |
| 65 | + startLatch.countDown(); |
| 66 | + taskResults.forEach(Futures::getUnchecked); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments