Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ConfigUtil#getString ConcurrentModificationException #6841

Merged
merged 7 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@

package io.opentelemetry.api.internal;

import java.util.ConcurrentModificationException;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import javax.annotation.Nullable;

/**
Expand All @@ -19,6 +21,17 @@ public final class ConfigUtil {

private ConfigUtil() {}

/**
* Returns a copy of system properties which is safe to iterate over.
*
* <p>In java 8 and android environments, iterating through system properties may trigger {@link
* ConcurrentModificationException}. This method ensures callers can iterate safely without risk
* of exception. See https://github.com/open-telemetry/opentelemetry-java/issues/6732 for details.
*/
public static Properties safeSystemProperties() {
return (Properties) System.getProperties().clone();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cloning seems to be the simplest way to accommodate various use cases. Anything other option that returns Properties ends up mimicking the logic of clone() anyway. If clone() ends up being too expensive (I doubt it), we can cache a copy.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm ok with it

ConfigUtil.getString(..) is already slow (too slow to be used on the hotpath) since it normalizes all the entry keys on each call

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If clone() ends up being too expensive

clone is only needed on jdk8 and android so we could skip it on other jdks if we so wish. Untested code follows

private static final CLONE_PROPERTIES = System.getProperty("java.version").equals("0") // android
  || System.getProperty("java.specification.version").startsWith("1."); // jdk8

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clone is only needed on jdk8 and android so we could skip it on other jdks if we so wish.

That's true. I'd prefer to keep that in our back pocket in case we need it. As a general rule, I think we avoid runtime-specific code unless we have a strong reason (subjective definition of "strong").

}

/**
* Return the system property or environment variable for the {@code key}.
*
Expand All @@ -33,8 +46,11 @@ private ConfigUtil() {}
*/
public static String getString(String key, String defaultValue) {
String normalizedKey = normalizePropertyKey(key);

// Cloning in order to avoid ConcurrentModificationException
// see https://github.com/open-telemetry/opentelemetry-java/issues/6732
String systemProperty =
System.getProperties().entrySet().stream()
safeSystemProperties().entrySet().stream()
.filter(entry -> normalizedKey.equals(normalizePropertyKey(entry.getKey().toString())))
.map(entry -> entry.getValue().toString())
.findFirst()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,15 @@
package io.opentelemetry.api.internal;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.SetSystemProperty;

Expand Down Expand Up @@ -56,4 +64,45 @@ void defaultIfnull() {
assertThat(ConfigUtil.defaultIfNull("val1", "val2")).isEqualTo("val1");
assertThat(ConfigUtil.defaultIfNull(null, "val2")).isEqualTo("val2");
}

@Test
@SuppressWarnings("ReturnValueIgnored")
void systemPropertiesConcurrentAccess() throws ExecutionException, InterruptedException {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test fails on java 8 if you call System.getProperties() instead of ConfigUtil#safeSystemProperties().

int threads = 4;
ExecutorService executor = Executors.newFixedThreadPool(threads);
try {
int cycles = 1000;
CountDownLatch latch = new CountDownLatch(1);
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < threads; i++) {
futures.add(
executor.submit(
() -> {
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

for (int j = 0; j < cycles; j++) {
String property = "prop " + j;
System.setProperty(property, "a");
System.getProperties().remove(property);
}
}));
}

latch.countDown();
for (int i = 0; i < cycles; i++) {
assertThatCode(() -> ConfigUtil.getString("x", "y")).doesNotThrowAnyException();
}

for (Future<?> future : futures) {
future.get();
}

} finally {
executor.shutdownNow();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ public final class DefaultConfigProperties implements ConfigProperties {
* priority over environment variables.
*/
public static DefaultConfigProperties create(Map<String, String> defaultProperties) {
return new DefaultConfigProperties(System.getProperties(), System.getenv(), defaultProperties);
return new DefaultConfigProperties(
ConfigUtil.safeSystemProperties(), System.getenv(), defaultProperties);
}

/**
Expand Down
Loading