|
| 1 | +/* |
| 2 | + * Licensed to Elasticsearch B.V. under one or more contributor |
| 3 | + * license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch B.V. licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package co.elastic.clients.json; |
| 21 | + |
| 22 | +import org.junit.Assert; |
| 23 | +import org.junit.Test; |
| 24 | + |
| 25 | +import java.util.concurrent.CompletableFuture; |
| 26 | + |
| 27 | +public class LazyDeserializerTest extends Assert { |
| 28 | + |
| 29 | + |
| 30 | + @Test |
| 31 | + public void testConcurrentInit() throws Exception { |
| 32 | + // See https://github.com/elastic/elasticsearch-java/issues/58 |
| 33 | + |
| 34 | + final LazyDeserializer<String> ld = new LazyDeserializer<>(JsonpDeserializer::stringDeserializer); |
| 35 | + |
| 36 | + CompletableFuture<JsonpDeserializer<String>> fut1; |
| 37 | + CompletableFuture<JsonpDeserializer<String>> fut2; |
| 38 | + |
| 39 | + // Lock the mutex and start 2 threads that will compete for it. |
| 40 | + synchronized (ld) { |
| 41 | + fut1 = futureUnwrap(ld); |
| 42 | + fut2 = futureUnwrap(ld); |
| 43 | + } |
| 44 | + |
| 45 | + // We should see the same non-null results everywhere |
| 46 | + assertNotNull(fut1.get()); |
| 47 | + assertNotNull(fut2.get()); |
| 48 | + |
| 49 | + final JsonpDeserializer<String> unwrapped = ld.unwrap(); |
| 50 | + assertEquals(unwrapped, fut1.get()); |
| 51 | + assertEquals(unwrapped, fut2.get()); |
| 52 | + |
| 53 | + } |
| 54 | + |
| 55 | + private CompletableFuture<JsonpDeserializer<String>> futureUnwrap(LazyDeserializer<String> d) { |
| 56 | + |
| 57 | + final CompletableFuture<JsonpDeserializer<String>> result = new CompletableFuture<>(); |
| 58 | + |
| 59 | + new Thread(() -> { |
| 60 | + try { |
| 61 | + result.complete(d.unwrap()); |
| 62 | + } catch (Throwable e) { |
| 63 | + result.completeExceptionally(e); |
| 64 | + } |
| 65 | + }).start(); |
| 66 | + |
| 67 | + return result; |
| 68 | + } |
| 69 | +} |
0 commit comments