diff --git a/client-v2/src/main/java/com/clickhouse/client/api/internal/BaseCollectionConverter.java b/client-v2/src/main/java/com/clickhouse/client/api/internal/BaseCollectionConverter.java index 7ea080bee..da9d2c867 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/internal/BaseCollectionConverter.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/internal/BaseCollectionConverter.java @@ -1,6 +1,7 @@ package com.clickhouse.client.api.internal; import com.clickhouse.client.api.ClickHouseException; +import com.clickhouse.data.ClickHouseColumn; import java.io.IOException; import java.lang.reflect.Array; @@ -8,6 +9,11 @@ import java.util.Deque; import java.util.List; +/** + * Walks a (possibly nested) collection and writes it into an accumulator. + * The accumulator and the column are passed to each call, so an instance holds no + * per-conversion state and can be used by many threads at the same time. + */ public abstract class BaseCollectionConverter { public static final String ARRAY_START = "["; public static final String ARRAY_END = "]"; @@ -18,17 +24,15 @@ protected BaseCollectionConverter(String itemDelimiter) { this.itemDelimiter = itemDelimiter; } - protected abstract void setAccumulator(ACC acc); + protected abstract void append(ACC acc, String str); - protected abstract void append(String str); + protected abstract String buildString(ACC acc); - protected abstract String buildString(); + protected abstract void onStart(ListConversionState state, ACC acc, ClickHouseColumn column); - protected abstract void onStart(ListConversionState state); + protected abstract void onEnd(ListConversionState state, ACC acc, ClickHouseColumn column); - protected abstract void onEnd(ListConversionState state); - - protected abstract void onItem(Object item, ListConversionState state); + protected abstract void onItem(Object item, ListConversionState state, ACC acc, ClickHouseColumn column); protected abstract String onEmptyCollection(); @@ -40,17 +44,16 @@ protected BaseCollectionConverter(String itemDelimiter) { protected abstract Object getNext(ListConversionState state); - public final String convert(LIST value, ACC acc) { + public final String convert(LIST value, ACC acc, ClickHouseColumn column) { if (isEmpty(value)) { return onEmptyCollection(); } - setAccumulator(acc); Deque> stack = new ArrayDeque<>(); ListConversionState state = new ListConversionState<>(value, listSize(value)); while (state != null) { if (state.isFirst()) { - onStart(state); + onStart(state, acc, column); } if (state.hasNext()) { Object item = getNext(state); @@ -60,21 +63,21 @@ public final String convert(LIST value, ACC acc) { LIST list = (LIST) item; state = new ListConversionState<>(list, listSize(list)); } else { - onItem(item, state); + onItem(item, state, acc, column); if (state.hasNext()) { - append(itemDelimiter); + append(acc, itemDelimiter); } } } else { - onEnd(state); + onEnd(state, acc, column); state = stack.isEmpty() ? null : stack.pop(); if (state != null && state.hasNext()) { - append(itemDelimiter); + append(acc, itemDelimiter); } } } - return buildString(); + return buildString(acc); } public static final class ListConversionState { @@ -167,19 +170,12 @@ protected Object getNext(ListConversionState> state) { public abstract static class BaseCollectionWriter extends BaseCollectionConverter { - protected Appendable appendable; - protected BaseCollectionWriter(String itemDelimiter) { super(itemDelimiter); } @Override - protected void setAccumulator(Appendable appendable) { - this.appendable = appendable; - } - - @Override - protected void append(String str) { + protected void append(Appendable appendable, String str) { try { appendable.append(str); } catch (IOException e) { @@ -188,12 +184,12 @@ protected void append(String str) { } @Override - protected String buildString() { + protected String buildString(Appendable appendable) { return appendable.toString(); } @Override - protected void onStart(ListConversionState state) { + protected void onStart(ListConversionState state, Appendable appendable, ClickHouseColumn column) { try { appendable.append(ARRAY_START); } catch (IOException e) { @@ -202,7 +198,7 @@ protected void onStart(ListConversionState state) { } @Override - protected void onEnd(ListConversionState state) { + protected void onEnd(ListConversionState state, Appendable appendable, ClickHouseColumn column) { try { appendable.append(ARRAY_END); } catch (IOException e) { diff --git a/client-v2/src/main/java/com/clickhouse/client/api/internal/DataTypeConverter.java b/client-v2/src/main/java/com/clickhouse/client/api/internal/DataTypeConverter.java index 713e9cc43..51cbbf38e 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/internal/DataTypeConverter.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/internal/DataTypeConverter.java @@ -29,7 +29,9 @@ /** * Class designed to convert different data types to Java objects. * First use-case is to convert ClickHouse data types to String representation. - * Note: class is not thread-safe to avoid extra object creation. + * Note: this class is thread-safe. Conversion state is passed in method parameters, not kept in fields, + * so one instance (for example, {@link #INSTANCE}) can be used by many threads at the same time. + * A subclass that is shared in the same way must not keep per-call state in fields. */ public class DataTypeConverter { @@ -234,11 +236,11 @@ public String ipvToString(Object value, ClickHouseColumn column) { public String arrayToString(Object value, ClickHouseColumn column) { if (value instanceof BinaryStreamReader.ArrayValue) { - return listAsStringWriter.convertAndReset(((BinaryStreamReader.ArrayValue) value).asList(), new StringBuilder(), column); + return listAsStringWriter.convert(((BinaryStreamReader.ArrayValue) value).asList(), new StringBuilder(), column); } else if (value.getClass().isArray()) { - return arrayAsStringWriter.convertAndReset(value, new StringBuilder(), column); + return arrayAsStringWriter.convert(value, new StringBuilder(), column); } else if (value instanceof List) { - return listAsStringWriter.convertAndReset((List) value, new StringBuilder(), column); + return listAsStringWriter.convert((List) value, new StringBuilder(), column); } return value.toString(); } @@ -576,55 +578,29 @@ private static void appendEnquotedArrayElement(String value, ClickHouseColumn el } private final class ArrayAsStringWriter extends BaseCollectionConverter.BaseArrayWriter { - private ClickHouseColumn column; ArrayAsStringWriter() { super(); } - public void setColumn(ClickHouseColumn column) { - this.column = column; - } - - @Override - protected void onItem(Object item, ListConversionState state) { + protected void onItem(Object item, ListConversionState state, Appendable appendable, ClickHouseColumn column) { if (item == null) { - append(NULL); + append(appendable, NULL); return; } ClickHouseColumn elementColumn = column.getArrayBaseColumn() == null ? column : column.getArrayBaseColumn(); String str = DataTypeConverter.this.convertToString(item, elementColumn); appendEnquotedArrayElement(str, elementColumn, appendable); } - - public String convertAndReset(Object list, Appendable acc, ClickHouseColumn column) { - // Save current state to handle re-entrancy (nested array conversion) - ClickHouseColumn prevColumn = this.column; - Appendable prevAppendable = this.appendable; - try { - setColumn(column); - return super.convert(list, acc); - } finally { - // Restore previous state for re-entrant calls - this.column = prevColumn; - setAccumulator(prevAppendable); - } - } } private final class ListAsStringWriter extends BaseCollectionConverter.BaseListWriter { - private ClickHouseColumn column; - - public void setColumn(ClickHouseColumn column) { - this.column = column; - } - @Override - protected void onItem(Object item, ListConversionState> state) { + protected void onItem(Object item, ListConversionState> state, Appendable appendable, ClickHouseColumn column) { if (item == null) { - append(NULL); + append(appendable, NULL); return; } ClickHouseColumn elementColumn = column.getArrayBaseColumn() == null ? column : column.getArrayBaseColumn(); @@ -632,19 +608,5 @@ protected void onItem(Object item, ListConversionState> state) { appendEnquotedArrayElement(str, elementColumn, appendable); } - - public String convertAndReset(List list, Appendable acc, ClickHouseColumn column) { - // Save current state to handle re-entrancy (nested array conversion) - ClickHouseColumn prevColumn = this.column; - Appendable prevAppendable = this.appendable; - try { - setColumn(column); - return super.convert(list, acc); - } finally { - // Restore previous state for re-entrant calls - this.column = prevColumn; - setAccumulator(prevAppendable); - } - } } } diff --git a/client-v2/src/test/java/com/clickhouse/client/api/internal/DataTypeConverterTest.java b/client-v2/src/test/java/com/clickhouse/client/api/internal/DataTypeConverterTest.java index 40416db86..b6553d81d 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/internal/DataTypeConverterTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/internal/DataTypeConverterTest.java @@ -1,5 +1,6 @@ package com.clickhouse.client.api.internal; +import com.clickhouse.client.api.data_formats.internal.BinaryStreamReader; import com.clickhouse.data.ClickHouseColumn; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -13,9 +14,16 @@ import java.util.Arrays; import java.util.Collections; import java.util.Date; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; @Test(groups = {"unit"}) public class DataTypeConverterTest { @@ -195,6 +203,77 @@ public void testVariantTwoDimensionalGeoToString() { "[[1.0, 2.0], [3.0, 4.0]]"); } + @DataProvider(name = "arrayContainers") + public static Object[][] arrayContainers() { + return new Object[][] { + {(Function) Arrays::asList}, + {(Function) items -> items}, + {(Function) items -> { + BinaryStreamReader.ArrayValue array = new BinaryStreamReader.ArrayValue(Object.class, items.length); + for (int i = 0; i < items.length; i++) { + array.set(i, items[i]); + } + return array; + }}, + }; + } + + @Test(dataProvider = "arrayContainers") + public void testArrayToStringWithSharedInstanceInParallel(Function container) throws Exception { + DataTypeConverter converter = DataTypeConverter.INSTANCE; + BlockingValue first = new BlockingValue("1"); + BlockingValue second = new BlockingValue("b"); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future intArray = executor.submit(() -> converter.convertToString( + container.apply(new Object[] {first, 2}), ClickHouseColumn.of("v", "Array(Int32)"))); + first.awaitEntered(); + Future strArray = executor.submit(() -> converter.convertToString( + container.apply(new Object[] {second, "c"}), ClickHouseColumn.of("v", "Array(String)"))); + second.awaitEntered(); + + first.release(); + assertEquals(intArray.get(10, TimeUnit.SECONDS), "[1, 2]"); + second.release(); + assertEquals(strArray.get(10, TimeUnit.SECONDS), "['b', 'c']"); + } finally { + executor.shutdownNow(); + } + } + + /** Array element whose conversion waits until the test releases it, to interleave two conversions. */ + private static final class BlockingValue { + private final String text; + private final CountDownLatch entered = new CountDownLatch(1); + private final CountDownLatch released = new CountDownLatch(1); + + BlockingValue(String text) { + this.text = text; + } + + void awaitEntered() throws InterruptedException { + assertTrue(entered.await(10, TimeUnit.SECONDS), "conversion did not start"); + } + + void release() { + released.countDown(); + } + + @Override + public String toString() { + entered.countDown(); + try { + if (!released.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("value was not released"); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + return text; + } + } + @DataProvider(name = "queryParameters") public static Object[][] queryParameters() { return new Object[][] { diff --git a/client-v2/src/test/java/com/clickhouse/client/query/QueryTests.java b/client-v2/src/test/java/com/clickhouse/client/query/QueryTests.java index 3d48ceeb5..4276a9213 100644 --- a/client-v2/src/test/java/com/clickhouse/client/query/QueryTests.java +++ b/client-v2/src/test/java/com/clickhouse/client/query/QueryTests.java @@ -2127,6 +2127,38 @@ public void testConcurrentQueries() throws Exception{ Assert.assertEquals(latch.getCount(), 0); } + @Test(groups = {"integration"}) + public void testGetStringOfArraysInParallelReaders() throws Exception { + final int concurrency = 4; + final int rows = 10_000; + final String sql = "SELECT number, [toString(number), 'x'] AS s, [number, number + 1] AS n FROM numbers(" + rows + ")"; + ExecutorService executor = Executors.newFixedThreadPool(concurrency); + try { + List> futures = new ArrayList<>(); + for (int i = 0; i < concurrency; i++) { + futures.add(executor.submit(() -> { + int count = 0; + try (QueryResponse response = client.query(sql).get(); + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response)) { + while (reader.hasNext()) { + reader.next(); + long number = reader.getLong("number"); + Assert.assertEquals(reader.getString("s"), "['" + number + "', 'x']"); + Assert.assertEquals(reader.getString("n"), "[" + number + ", " + (number + 1) + "]"); + count++; + } + } + return count; + })); + } + for (Future future : futures) { + Assert.assertEquals(future.get(30, TimeUnit.SECONDS).intValue(), rows); + } + } finally { + executor.shutdownNow(); + } + } + @Test(groups = {"integration"}) public void testQueryReadToPOJO() { int limit = 10; diff --git a/history/latest/2728.md b/history/latest/2728.md new file mode 100644 index 000000000..332bf9555 --- /dev/null +++ b/history/latest/2728.md @@ -0,0 +1,7 @@ +- **[client-v2, jdbc-v2]** Fixed `getString()` on array values (`Array`, `QBit`, and arrays in `Variant` or `Dynamic`) + when readers, `GenericRecord` or `ResultSet` objects in different threads convert them at the same time. All of them + share one `DataTypeConverter`, and its array writers kept the current column and output buffer in fields. Parallel + conversions changed each other's state: a result had wrong quotes or values from another thread, or the call failed + with a `NullPointerException`. The writers now get the column and the buffer as method parameters, so + `DataTypeConverter` keeps no conversion state and is thread-safe. + (https://github.com/ClickHouse/clickhouse-java/issues/2728)