Simplify Map operations using computeIfAbsent (#4020)

If the specified key is not already associated with a value (or is mapped to null), the given mapping function computes the value.

Signed-off-by: Wouter Born <github@maindrain.net>
This commit is contained in:
Wouter Born 2024-02-06 20:34:05 +01:00 committed by GitHub
parent 823f993f56
commit f4e83693fb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 30 additions and 66 deletions

View File

@ -18,6 +18,7 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -154,11 +155,8 @@ public class RuleSupportScriptExtension implements ScriptExtensionProvider {
return obj; return obj;
} }
Map<String, Object> objects = objectCache.get(scriptIdentifier); Map<String, Object> objects = Objects
if (objects == null) { .requireNonNull(objectCache.computeIfAbsent(scriptIdentifier, k -> new HashMap<>()));
objects = new HashMap<>();
objectCache.put(scriptIdentifier, objects);
}
obj = objects.get(type); obj = objects.get(type);
if (obj != null) { if (obj != null) {

View File

@ -20,6 +20,7 @@ import java.util.HashSet;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -376,11 +377,8 @@ public class RuleRegistryImpl extends AbstractRegistry<Rule, String, RuleProvide
*/ */
private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) { private void updateRuleTemplateMapping(String templateUID, String ruleUID, boolean resolved) {
synchronized (this) { synchronized (this) {
Set<String> ruleUIDs = mapTemplateToRules.get(templateUID); Set<String> ruleUIDs = Objects
if (ruleUIDs == null) { .requireNonNull(mapTemplateToRules.computeIfAbsent(templateUID, k -> new HashSet<>()));
ruleUIDs = new HashSet<>();
mapTemplateToRules.put(templateUID, ruleUIDs);
}
if (resolved) { if (resolved) {
ruleUIDs.remove(ruleUID); ruleUIDs.remove(ruleUID);
} else { } else {

View File

@ -23,6 +23,7 @@ import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -252,11 +253,7 @@ public abstract class AbstractFileProvider<@NonNull E> implements Provider<E> {
} }
} else { } else {
synchronized (urls) { synchronized (urls) {
List<URL> value = urls.get(parserType); List<URL> value = Objects.requireNonNull(urls.computeIfAbsent(parserType, k -> new ArrayList<>()));
if (value == null) {
value = new ArrayList<>();
urls.put(parserType, value);
}
value.add(url); value.add(url);
} }
logger.debug("Parser {} not available", parserType, new Exception()); logger.debug("Parser {} not available", parserType, new Exception());

View File

@ -16,6 +16,7 @@ import java.io.File;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.service.WatchService; import org.openhab.core.service.WatchService;
@ -35,11 +36,8 @@ public class WatchServiceUtil {
WatchService watchService) { WatchService watchService) {
AutomationWatchService aws = null; AutomationWatchService aws = null;
synchronized (WATCH_SERVICES) { synchronized (WATCH_SERVICES) {
Map<String, AutomationWatchService> watchers = WATCH_SERVICES.get(provider); Map<String, AutomationWatchService> watchers = Objects
if (watchers == null) { .requireNonNull(WATCH_SERVICES.computeIfAbsent(provider, k -> new HashMap<>()));
watchers = new HashMap<>();
WATCH_SERVICES.put(provider, watchers);
}
if (watchers.get(watchingDir) == null) { if (watchers.get(watchingDir) == null) {
aws = new AutomationWatchService(provider, watchService, watchingDir); aws = new AutomationWatchService(provider, watchService, watchingDir);
watchers.put(watchingDir, aws); watchers.put(watchingDir, aws);

View File

@ -19,6 +19,7 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
@ -78,10 +79,8 @@ public abstract class AbstractXmlBasedProvider<@NonNull T_ID, @NonNull T_OBJECT
if (objectList.isEmpty()) { if (objectList.isEmpty()) {
return; return;
} }
List<T_OBJECT> objects = acquireObjects(bundle); List<T_OBJECT> objects = Objects
if (objects == null) { .requireNonNull(bundleObjectMap.computeIfAbsent(bundle, k -> new CopyOnWriteArrayList<>()));
return;
}
objects.addAll(objectList); objects.addAll(objectList);
for (T_OBJECT object : objectList) { for (T_OBJECT object : objectList) {
// just make sure no old entry remains in the cache // just make sure no old entry remains in the cache
@ -89,15 +88,6 @@ public abstract class AbstractXmlBasedProvider<@NonNull T_ID, @NonNull T_OBJECT
} }
} }
private @Nullable List<T_OBJECT> acquireObjects(Bundle bundle) {
List<T_OBJECT> objects = bundleObjectMap.get(bundle);
if (objects == null) {
objects = new CopyOnWriteArrayList<>();
bundleObjectMap.put(bundle, objects);
}
return objects;
}
/** /**
* Gets the object with the given key. * Gets the object with the given key.
* *

View File

@ -16,6 +16,7 @@ import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -89,24 +90,17 @@ public class GenericItemChannelLinkProvider extends AbstractProvider<ItemChannel
} }
ItemChannelLink itemChannelLink = new ItemChannelLink(itemName, channelUIDObject, configuration); ItemChannelLink itemChannelLink = new ItemChannelLink(itemName, channelUIDObject, configuration);
Set<String> itemNames = contextMap.get(context); Set<String> itemNames = Objects.requireNonNull(contextMap.computeIfAbsent(context, k -> new HashSet<>()));
if (itemNames == null) {
itemNames = new HashSet<>();
contextMap.put(context, itemNames);
}
itemNames.add(itemName); itemNames.add(itemName);
if (previousItemNames != null) { if (previousItemNames != null) {
previousItemNames.remove(itemName); previousItemNames.remove(itemName);
} }
Map<ChannelUID, ItemChannelLink> links = itemChannelLinkMap.get(itemName); // Create a HashMap with an initial capacity of 2 (the default is 16) to save memory because most items have
if (links == null) { // only one channel. A capacity of 2 is enough to avoid resizing the HashMap in most cases, whereas 1 would
// Create a HashMap with an initial capacity of 2 (the default is 16) to save memory // trigger a resize as soon as one element is added.
// because most items have only one channel. A capacity of 2 is enough to avoid Map<ChannelUID, ItemChannelLink> links = Objects
// resizing the HashMap in most cases, whereas 1 would trigger a resize as soon as .requireNonNull(itemChannelLinkMap.computeIfAbsent(itemName, k -> new HashMap<>(2)));
// one element is added.
itemChannelLinkMap.put(itemName, links = new HashMap<>(2));
}
ItemChannelLink oldLink = links.put(channelUIDObject, itemChannelLink); ItemChannelLink oldLink = links.put(channelUIDObject, itemChannelLink);
if (oldLink == null) { if (oldLink == null) {

View File

@ -22,6 +22,7 @@ import java.util.Dictionary;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate; import java.util.function.Predicate;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -264,11 +265,8 @@ public class JavaOSGiTest extends JavaTest {
} }
private void saveServiceRegistration(final String interfaceName, final ServiceRegistration<?> srvReg) { private void saveServiceRegistration(final String interfaceName, final ServiceRegistration<?> srvReg) {
List<ServiceRegistration<?>> regs = registeredServices.get(interfaceName); List<ServiceRegistration<?>> regs = Objects
if (regs == null) { .requireNonNull(registeredServices.computeIfAbsent(interfaceName, k -> new ArrayList<>()));
regs = new ArrayList<>();
registeredServices.put(interfaceName, regs);
}
regs.add(srvReg); regs.add(srvReg);
} }

View File

@ -16,6 +16,7 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -73,18 +74,10 @@ public abstract class AbstractLinkRegistry<L extends AbstractLink, P extends Pro
try { try {
Set<L> set; Set<L> set;
set = itemNameToLink.get(itemName); set = Objects.requireNonNull(itemNameToLink.computeIfAbsent(itemName, k -> new HashSet<>()));
if (set == null) {
set = new HashSet<>();
itemNameToLink.put(itemName, set);
}
set.add(element); set.add(element);
set = linkedUidToLink.get(linkedUid); set = Objects.requireNonNull(linkedUidToLink.computeIfAbsent(linkedUid, k -> new HashSet<>()));
if (set == null) {
set = new HashSet<>();
linkedUidToLink.put(linkedUid, set);
}
set.add(element); set.add(element);
} finally { } finally {
toLinkLock.writeLock().unlock(); toLinkLock.writeLock().unlock();

View File

@ -15,6 +15,7 @@ package org.openhab.core.internal.common;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@ -86,11 +87,8 @@ public class SafeCallManagerImpl implements SafeCallManager {
@Override @Override
public void enqueue(Invocation invocation) { public void enqueue(Invocation invocation) {
synchronized (queues) { synchronized (queues) {
Queue<Invocation> queue = queues.get(invocation.getIdentifier()); Queue<Invocation> queue = Objects
if (queue == null) { .requireNonNull(queues.computeIfAbsent(invocation.getIdentifier(), k -> new LinkedList<>()));
queue = new LinkedList<>();
queues.put(invocation.getIdentifier(), queue);
}
queue.add(invocation); queue.add(invocation);
} }
trigger(invocation.getIdentifier()); trigger(invocation.getIdentifier());