|
| 1 | +package com.marklogic.client.extra.okhttpclient; |
| 2 | + |
| 3 | +import com.marklogic.client.DatabaseClientFactory; |
| 4 | +import com.marklogic.client.test.Common; |
| 5 | +import org.junit.jupiter.api.Test; |
| 6 | + |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.List; |
| 9 | +import java.util.concurrent.ExecutorService; |
| 10 | +import java.util.concurrent.Executors; |
| 11 | +import java.util.concurrent.Future; |
| 12 | +import java.util.concurrent.TimeUnit; |
| 13 | + |
| 14 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 15 | + |
| 16 | +public class OkHttpClientConfiguratorTest { |
| 17 | + |
| 18 | + /** |
| 19 | + * Not a test exactly of OkHttp, but rather that multiple threads can add configurators and create clients without |
| 20 | + * encountering a ConcurrentModificationException, which used to occur due to the list of configurators in |
| 21 | + * DatabaseClientFactory not being synchronized. |
| 22 | + * |
| 23 | + * @throws Exception |
| 24 | + */ |
| 25 | + @Test |
| 26 | + void multipleThreads() throws Exception { |
| 27 | + final int clientsToCreate = 100; |
| 28 | + |
| 29 | + ExecutorService service = Executors.newFixedThreadPool(16); |
| 30 | + List<Future> futures = new ArrayList<>(); |
| 31 | + for (int i = 0; i < clientsToCreate; i++) { |
| 32 | + futures.add(service.submit(() -> { |
| 33 | + DatabaseClientFactory.addConfigurator((OkHttpClientConfigurator) client -> { |
| 34 | + client.callTimeout(10, TimeUnit.SECONDS); |
| 35 | + }); |
| 36 | + Common.newClient().release(); |
| 37 | + })); |
| 38 | + } |
| 39 | + |
| 40 | + int clientsCreated = 0; |
| 41 | + for (Future f : futures) { |
| 42 | + f.get(); |
| 43 | + clientsCreated++; |
| 44 | + } |
| 45 | + service.shutdown(); |
| 46 | + |
| 47 | + assertEquals(clientsToCreate, clientsCreated, "The expectation is that many threads can " + |
| 48 | + "add a configurator and create a client at the same time because DatabaseClientFactory " + |
| 49 | + "uses a synchronized list for the configurators. So all of the expected clients should be " + |
| 50 | + "created successfully with no concurrent modification errors occurring."); |
| 51 | + } |
| 52 | +} |
0 commit comments