From a49805c9acbfc2d964e527dc17e21f8ae01eafd2 Mon Sep 17 00:00:00 2001 From: zhangyangshuo Date: Wed, 17 Nov 2021 22:49:55 +0800 Subject: [PATCH] optimize the read lock caused by computeIfAbsent and synchronized --- .../java/io/trino/spi/type/TypeOperators.java | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/core/trino-spi/src/main/java/io/trino/spi/type/TypeOperators.java b/core/trino-spi/src/main/java/io/trino/spi/type/TypeOperators.java index c91e21584fd6..8bc95d1e87c1 100644 --- a/core/trino-spi/src/main/java/io/trino/spi/type/TypeOperators.java +++ b/core/trino-spi/src/main/java/io/trino/spi/type/TypeOperators.java @@ -69,7 +69,15 @@ public class TypeOperators public TypeOperators() { ConcurrentHashMap cache = new ConcurrentHashMap<>(); - this.cache = (operatorConvention, supplier) -> cache.computeIfAbsent(operatorConvention, key -> supplier.get()); + // optimize the read lock caused by computeIfAbsent + // this.cache = (operatorConvention, supplier) -> cache.computeIfAbsent(operatorConvention, key -> supplier.get()); + this.cache = (operatorConvention, supplier) -> { + Object value = cache.get(operatorConvention); + if (value == null) { + value = cache.computeIfAbsent(operatorConvention, key -> supplier.get()); + } + return value; + }; } public TypeOperators(BiFunction, Object> cache) @@ -181,10 +189,14 @@ public OperatorAdaptor(ScalarFunctionAdapter functionAdapter, OperatorConvention this.operatorConvention = operatorConvention; } - public synchronized MethodHandle get() + // optimize the read lock caused by synchronized + // public synchronized MethodHandle get() + public MethodHandle get() { if (adapted == null) { - adapted = adaptOperator(operatorConvention); + synchronized (this) { + adapted = adaptOperator(operatorConvention); + } } return adapted; }