Skip to content

Commit 195a86b

Browse files
committed
Use Map::computeIfAbsent where feasible
1 parent bc65f93 commit 195a86b

File tree

16 files changed

+61
-136
lines changed

16 files changed

+61
-136
lines changed

spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -342,8 +342,7 @@ protected CacheOperationMetadata getCacheOperationMetadata(
342342
CacheOperation operation, Method method, Class<?> targetClass) {
343343

344344
CacheOperationCacheKey cacheKey = new CacheOperationCacheKey(operation, method, targetClass);
345-
CacheOperationMetadata metadata = this.metadataCache.get(cacheKey);
346-
if (metadata == null) {
345+
return this.metadataCache.computeIfAbsent(cacheKey, ignored -> {
347346
KeyGenerator operationKeyGenerator;
348347
if (StringUtils.hasText(operation.getKeyGenerator())) {
349348
operationKeyGenerator = getBean(operation.getKeyGenerator(), KeyGenerator.class);
@@ -363,11 +362,9 @@ else if (StringUtils.hasText(operation.getCacheManager())) {
363362
operationCacheResolver = getCacheResolver();
364363
Assert.state(operationCacheResolver != null, "No CacheResolver/CacheManager set");
365364
}
366-
metadata = new CacheOperationMetadata(operation, method, targetClass,
365+
return new CacheOperationMetadata(operation, method, targetClass,
367366
operationKeyGenerator, operationCacheResolver);
368-
this.metadataCache.put(cacheKey, metadata);
369-
}
370-
return metadata;
367+
});
371368
}
372369

373370
/**

spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -273,13 +273,11 @@ public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDe
273273
"Expected [" + this.annotationType.getName() + "] to be present on " + sourceType);
274274
}
275275
AnnotationConverterKey converterKey = new AnnotationConverterKey(ann, sourceType.getObjectType());
276-
GenericConverter converter = cachedPrinters.get(converterKey);
277-
if (converter == null) {
276+
GenericConverter converter = cachedPrinters.computeIfAbsent(converterKey, key -> {
278277
Printer<?> printer = this.annotationFormatterFactory.getPrinter(
279-
converterKey.getAnnotation(), converterKey.getFieldType());
280-
converter = new PrinterConverter(this.fieldType, printer, FormattingConversionService.this);
281-
cachedPrinters.put(converterKey, converter);
282-
}
278+
key.getAnnotation(), key.getFieldType());
279+
return new PrinterConverter(this.fieldType, printer, FormattingConversionService.this);
280+
});
283281
return converter.convert(source, sourceType, targetType);
284282
}
285283

@@ -328,13 +326,11 @@ public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDe
328326
"Expected [" + this.annotationType.getName() + "] to be present on " + targetType);
329327
}
330328
AnnotationConverterKey converterKey = new AnnotationConverterKey(ann, targetType.getObjectType());
331-
GenericConverter converter = cachedParsers.get(converterKey);
332-
if (converter == null) {
329+
GenericConverter converter = cachedParsers.computeIfAbsent(converterKey, key -> {
333330
Parser<?> parser = this.annotationFormatterFactory.getParser(
334-
converterKey.getAnnotation(), converterKey.getFieldType());
335-
converter = new ParserConverter(this.fieldType, parser, FormattingConversionService.this);
336-
cachedParsers.put(converterKey, converter);
337-
}
331+
key.getAnnotation(), key.getFieldType());
332+
return new ParserConverter(this.fieldType, parser, FormattingConversionService.this);
333+
});
338334
return converter.convert(source, sourceType, targetType);
339335
}
340336

spring-context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -534,11 +534,7 @@ private Object invokeOperation(Method method, Object[] args) throws JMException,
534534

535535
String[] signature;
536536
synchronized (this.signatureCache) {
537-
signature = this.signatureCache.get(method);
538-
if (signature == null) {
539-
signature = JmxUtils.getMethodSignature(method);
540-
this.signatureCache.put(method, signature);
541-
}
537+
signature = this.signatureCache.computeIfAbsent(method, JmxUtils::getMethodSignature);
542538
}
543539

544540
return this.serverToUse.invoke(this.objectName, method.getName(), args, signature);

spring-context/src/main/java/org/springframework/ui/context/support/ResourceBundleThemeSource.java

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -143,17 +143,16 @@ public Theme getTheme(String themeName) {
143143
Theme theme = this.themeCache.get(themeName);
144144
if (theme == null) {
145145
synchronized (this.themeCache) {
146-
theme = this.themeCache.get(themeName);
147-
if (theme == null) {
148-
String basename = this.basenamePrefix + themeName;
146+
theme = this.themeCache.computeIfAbsent(themeName, key -> {
147+
String basename = this.basenamePrefix + key;
149148
MessageSource messageSource = createMessageSource(basename);
150-
theme = new SimpleTheme(themeName, messageSource);
151-
initParent(theme);
152-
this.themeCache.put(themeName, theme);
149+
Theme themeToUse = new SimpleTheme(key, messageSource);
150+
initParent(themeToUse);
153151
if (logger.isDebugEnabled()) {
154-
logger.debug("Theme created: name '" + themeName + "', basename [" + basename + "]");
152+
logger.debug("Theme created: name '" + key + "', basename [" + basename + "]");
155153
}
156-
}
154+
return themeToUse;
155+
});
157156
}
158157
}
159158
return theme;

spring-jms/src/main/java/org/springframework/jms/connection/CachingConnectionFactory.java

Lines changed: 15 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -47,6 +47,7 @@
4747
import org.springframework.util.Assert;
4848
import org.springframework.util.ClassUtils;
4949
import org.springframework.util.ObjectUtils;
50+
import org.springframework.util.function.ThrowingFunction;
5051

5152
/**
5253
* {@link SingleConnectionFactory} subclass that adds {@link Session} caching as well as
@@ -428,19 +429,13 @@ else if (isCacheConsumers()) {
428429

429430
private MessageProducer getCachedProducer(@Nullable Destination dest) throws JMSException {
430431
DestinationCacheKey cacheKey = (dest != null ? new DestinationCacheKey(dest) : null);
431-
MessageProducer producer = this.cachedProducers.get(cacheKey);
432-
if (producer != null) {
433-
if (logger.isTraceEnabled()) {
434-
logger.trace("Found cached JMS MessageProducer for destination [" + dest + "]: " + producer);
435-
}
436-
}
437-
else {
438-
producer = this.target.createProducer(dest);
432+
MessageProducer producer = this.cachedProducers.computeIfAbsent(cacheKey, (ThrowingFunction<DestinationCacheKey, MessageProducer>) ignored -> {
433+
MessageProducer producerToUse = this.target.createProducer(dest);
439434
if (logger.isDebugEnabled()) {
440-
logger.debug("Registering cached JMS MessageProducer for destination [" + dest + "]: " + producer);
435+
logger.debug("Registering cached JMS MessageProducer for destination [" + dest + "]: " + producerToUse);
441436
}
442-
this.cachedProducers.put(cacheKey, producer);
443-
}
437+
return producerToUse;
438+
});
444439
return new CachedMessageProducer(producer);
445440
}
446441

@@ -449,33 +444,28 @@ private MessageConsumer getCachedConsumer(Destination dest, @Nullable String sel
449444
@Nullable Boolean noLocal, @Nullable String subscription, boolean durable) throws JMSException {
450445

451446
ConsumerCacheKey cacheKey = new ConsumerCacheKey(dest, selector, noLocal, subscription, durable);
452-
MessageConsumer consumer = this.cachedConsumers.get(cacheKey);
453-
if (consumer != null) {
454-
if (logger.isTraceEnabled()) {
455-
logger.trace("Found cached JMS MessageConsumer for destination [" + dest + "]: " + consumer);
456-
}
457-
}
458-
else {
447+
MessageConsumer consumer = this.cachedConsumers.computeIfAbsent(cacheKey, (ThrowingFunction<ConsumerCacheKey, MessageConsumer>) ignored -> {
448+
MessageConsumer consumerToUse;
459449
if (dest instanceof Topic topic) {
460450
if (noLocal == null) {
461-
consumer = (durable ?
451+
consumerToUse = (durable ?
462452
this.target.createSharedDurableConsumer(topic, subscription, selector) :
463453
this.target.createSharedConsumer(topic, subscription, selector));
464454
}
465455
else {
466-
consumer = (durable ?
456+
consumerToUse = (durable ?
467457
this.target.createDurableSubscriber(topic, subscription, selector, noLocal) :
468458
this.target.createConsumer(dest, selector, noLocal));
469459
}
470460
}
471461
else {
472-
consumer = this.target.createConsumer(dest, selector);
462+
consumerToUse = this.target.createConsumer(dest, selector);
473463
}
474464
if (logger.isDebugEnabled()) {
475-
logger.debug("Registering cached JMS MessageConsumer for destination [" + dest + "]: " + consumer);
465+
logger.debug("Registering cached JMS MessageConsumer for destination [" + dest + "]: " + consumerToUse);
476466
}
477-
this.cachedConsumers.put(cacheKey, consumer);
478-
}
467+
return consumerToUse;
468+
});
479469
return new CachedMessageConsumer(consumer);
480470
}
481471

spring-messaging/src/main/java/org/springframework/messaging/core/CachingDestinationResolverProxy.java

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -86,13 +86,10 @@ public void afterPropertiesSet() {
8686
*/
8787
@Override
8888
public D resolveDestination(String name) throws DestinationResolutionException {
89-
D destination = this.resolvedDestinationCache.get(name);
90-
if (destination == null) {
89+
return this.resolvedDestinationCache.computeIfAbsent(name, key -> {
9190
Assert.state(this.targetDestinationResolver != null, "No target DestinationResolver set");
92-
destination = this.targetDestinationResolver.resolveDestination(name);
93-
this.resolvedDestinationCache.put(name, destination);
94-
}
95-
return destination;
91+
return this.targetDestinationResolver.resolveDestination(key);
92+
});
9693
}
9794

9895
}

spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/reactive/AbstractNamedValueMethodArgumentResolver.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -126,13 +126,7 @@ else if (namedValueInfo.required && !nestedParameter.isOptional()) {
126126
* Obtain the named value for the given method parameter.
127127
*/
128128
private NamedValueInfo getNamedValueInfo(MethodParameter parameter) {
129-
NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter);
130-
if (namedValueInfo == null) {
131-
namedValueInfo = createNamedValueInfo(parameter);
132-
namedValueInfo = updateNamedValueInfo(parameter, namedValueInfo);
133-
this.namedValueInfoCache.put(parameter, namedValueInfo);
134-
}
135-
return namedValueInfo;
129+
return this.namedValueInfoCache.computeIfAbsent(parameter, key -> updateNamedValueInfo(key, createNamedValueInfo(key)));
136130
}
137131

138132
/**

spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/AbstractNamedValueMethodArgumentResolver.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -136,13 +136,7 @@ else if (namedValueInfo.required && !nestedParameter.isOptional()) {
136136
* Obtain the named value for the given method parameter.
137137
*/
138138
private NamedValueInfo getNamedValueInfo(MethodParameter parameter) {
139-
NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter);
140-
if (namedValueInfo == null) {
141-
namedValueInfo = createNamedValueInfo(parameter);
142-
namedValueInfo = updateNamedValueInfo(parameter, namedValueInfo);
143-
this.namedValueInfoCache.put(parameter, namedValueInfo);
144-
}
145-
return namedValueInfo;
139+
return this.namedValueInfoCache.computeIfAbsent(parameter, key -> updateNamedValueInfo(key, createNamedValueInfo(key)));
146140
}
147141

148142
/**

spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/AbstractExceptionHandlerMethodResolver.java

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2021 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -120,11 +120,7 @@ public Method resolveMethod(Throwable exception) {
120120
*/
121121
@Nullable
122122
public Method resolveMethodByExceptionType(Class<? extends Throwable> exceptionType) {
123-
Method method = this.exceptionLookupCache.get(exceptionType);
124-
if (method == null) {
125-
method = getMappedMethod(exceptionType);
126-
this.exceptionLookupCache.put(exceptionType, method);
127-
}
123+
Method method = this.exceptionLookupCache.computeIfAbsent(exceptionType, this::getMappedMethod);
128124
return (method != NO_MATCHING_EXCEPTION_HANDLER_METHOD ? method : null);
129125
}
130126

spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/AbstractMethodMessageHandler.java

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -634,11 +634,7 @@ protected InvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handler
634634
logger.debug("Searching methods to handle " + exception.getClass().getSimpleName());
635635
}
636636
Class<?> beanType = handlerMethod.getBeanType();
637-
AbstractExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(beanType);
638-
if (resolver == null) {
639-
resolver = createExceptionHandlerMethodResolverFor(beanType);
640-
this.exceptionHandlerCache.put(beanType, resolver);
641-
}
637+
AbstractExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.computeIfAbsent(beanType, this::createExceptionHandlerMethodResolverFor);
642638
Method method = resolver.resolveMethod(exception);
643639
if (method != null) {
644640
return new InvocableHandlerMethod(handlerMethod.getBean(), method);

spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/InvocableHelper.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -152,11 +152,7 @@ public InvocableHandlerMethod initExceptionHandlerMethod(HandlerMethod handlerMe
152152
logger.debug("Searching for methods to handle " + ex.getClass().getSimpleName());
153153
}
154154
Class<?> beanType = handlerMethod.getBeanType();
155-
AbstractExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(beanType);
156-
if (resolver == null) {
157-
resolver = this.exceptionMethodResolverFactory.apply(beanType);
158-
this.exceptionHandlerCache.put(beanType, resolver);
159-
}
155+
AbstractExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.computeIfAbsent(beanType, this.exceptionMethodResolverFactory);
160156
InvocableHandlerMethod exceptionHandlerMethod = null;
161157
Method method = resolver.resolveMethod(ex);
162158
if (method != null) {

spring-orm/src/main/java/org/springframework/orm/hibernate5/SpringBeanContainer.java

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -101,11 +101,7 @@ public <B> ContainedBean<B> getBean(
101101

102102
SpringContainedBean<?> bean;
103103
if (lifecycleOptions.canUseCachedReferences()) {
104-
bean = this.beanCache.get(beanType);
105-
if (bean == null) {
106-
bean = createBean(beanType, lifecycleOptions, fallbackProducer);
107-
this.beanCache.put(beanType, bean);
108-
}
104+
bean = this.beanCache.computeIfAbsent(beanType, ignored -> createBean(beanType, lifecycleOptions, fallbackProducer));
109105
}
110106
else {
111107
bean = createBean(beanType, lifecycleOptions, fallbackProducer);
@@ -120,11 +116,7 @@ public <B> ContainedBean<B> getBean(
120116

121117
SpringContainedBean<?> bean;
122118
if (lifecycleOptions.canUseCachedReferences()) {
123-
bean = this.beanCache.get(name);
124-
if (bean == null) {
125-
bean = createBean(name, beanType, lifecycleOptions, fallbackProducer);
126-
this.beanCache.put(name, bean);
127-
}
119+
bean = this.beanCache.computeIfAbsent(name, ignored -> createBean(name, beanType, lifecycleOptions, fallbackProducer));
128120
}
129121
else {
130122
bean = createBean(name, beanType, lifecycleOptions, fallbackProducer);

spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -155,13 +155,7 @@ else if (namedValueInfo.required && !nestedParameter.isOptional()) {
155155
* Obtain the named value for the given method parameter.
156156
*/
157157
private NamedValueInfo getNamedValueInfo(MethodParameter parameter) {
158-
NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter);
159-
if (namedValueInfo == null) {
160-
namedValueInfo = createNamedValueInfo(parameter);
161-
namedValueInfo = updateNamedValueInfo(parameter, namedValueInfo);
162-
this.namedValueInfoCache.put(parameter, namedValueInfo);
163-
}
164-
return namedValueInfo;
158+
return this.namedValueInfoCache.computeIfAbsent(parameter, key -> updateNamedValueInfo(key, createNamedValueInfo(key)));
165159
}
166160

167161
/**

spring-web/src/main/java/org/springframework/web/service/invoker/AbstractNamedValueArgumentResolver.java

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -103,16 +103,13 @@ public boolean resolve(
103103

104104
@Nullable
105105
private NamedValueInfo getNamedValueInfo(MethodParameter parameter, HttpRequestValues.Metadata requestValues) {
106-
NamedValueInfo info = this.namedValueInfoCache.get(parameter);
107-
if (info == null) {
108-
info = createNamedValueInfo(parameter, requestValues);
109-
if (info == null) {
106+
return this.namedValueInfoCache.computeIfAbsent(parameter, key -> {
107+
NamedValueInfo infoToUse = createNamedValueInfo(key, requestValues);
108+
if (infoToUse == null) {
110109
return null;
111110
}
112-
info = updateNamedValueInfo(parameter, info);
113-
this.namedValueInfoCache.put(parameter, info);
114-
}
115-
return info;
111+
return updateNamedValueInfo(key, infoToUse);
112+
});
116113
}
117114

118115
/**

spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractNamedValueArgumentResolver.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -126,13 +126,7 @@ public Mono<Object> resolveArgument(
126126
* Obtain the named value for the given method parameter.
127127
*/
128128
private NamedValueInfo getNamedValueInfo(MethodParameter parameter) {
129-
NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter);
130-
if (namedValueInfo == null) {
131-
namedValueInfo = createNamedValueInfo(parameter);
132-
namedValueInfo = updateNamedValueInfo(parameter, namedValueInfo);
133-
this.namedValueInfoCache.put(parameter, namedValueInfo);
134-
}
135-
return namedValueInfo;
129+
return this.namedValueInfoCache.computeIfAbsent(parameter, key -> updateNamedValueInfo(key, createNamedValueInfo(key)));
136130
}
137131

138132
/**

0 commit comments

Comments
 (0)