-
Notifications
You must be signed in to change notification settings - Fork 188
#4673 Make AtWithRho.get() thread-safe #5023
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
base: master
Are you sure you want to change the base?
Changes from 1 commit
f5a720f
a0a29a3
1346a5f
4278545
ecec171
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,18 +5,13 @@ | |
|
|
||
| package org.eolang; | ||
|
|
||
| import java.util.concurrent.atomic.AtomicReference; | ||
| import java.util.concurrent.locks.ReentrantLock; | ||
|
|
||
| /** | ||
| * The attribute that tries to copy object and set \rho to it if it has not already set. | ||
| * This attribute is NOT thread safe! | ||
| * | ||
| * @since 0.36.0 | ||
| * @todo #4673:30min The {@link AtWithRho#get()} is not thread safe. If multiple threads | ||
| * call get() concurrently when the underlying object lacks RHO, each thread will: | ||
| * 1. Pass the !ret.hasRho() check | ||
| * 2. Create its own copy via ret.copy() | ||
| * 3. Attempt to set RHO on its copy | ||
| * This results in different threads receiving different copies, violating the expectation | ||
| * that get() returns a consistent view of the attribute's value. | ||
| */ | ||
| final class AtWithRho implements Attr { | ||
| /** | ||
|
|
@@ -29,6 +24,16 @@ final class AtWithRho implements Attr { | |
| */ | ||
| private final Phi rho; | ||
|
|
||
| /** | ||
| * Cached result of {@link #get()} to guarantee a consistent view across threads. | ||
| */ | ||
| private final AtomicReference<Phi> cached; | ||
|
|
||
| /** | ||
| * Lock guarding the first initialization of {@link #cached}. | ||
| */ | ||
| private final ReentrantLock lock; | ||
|
|
||
| /** | ||
| * Ctor. | ||
| * @param attr Attribute | ||
|
|
@@ -37,6 +42,8 @@ final class AtWithRho implements Attr { | |
| AtWithRho(final Attr attr, final Phi rho) { | ||
| this.original = attr; | ||
| this.rho = rho; | ||
| this.cached = new AtomicReference<>(); | ||
| this.lock = new ReentrantLock(); | ||
| } | ||
|
|
||
| @Override | ||
|
|
@@ -49,16 +56,29 @@ public Attr copy(final Phi self) { | |
|
|
||
| @Override | ||
| public Phi get() { | ||
| Phi ret = this.original.get(); | ||
| if (!ret.hasRho()) { | ||
| ret = ret.copy(); | ||
| ret.put(Phi.RHO, this.rho); | ||
| Phi ret = this.cached.get(); | ||
| if (ret == null) { | ||
| this.lock.lock(); | ||
| try { | ||
| ret = this.cached.get(); | ||
| if (ret == null) { | ||
| ret = this.original.get(); | ||
| if (!ret.hasRho()) { | ||
| ret = ret.copy(); | ||
| ret.put(Phi.RHO, this.rho); | ||
| } | ||
| this.cached.set(ret); | ||
| } | ||
| } finally { | ||
| this.lock.unlock(); | ||
| } | ||
| } | ||
| return ret; | ||
| } | ||
|
|
||
| @Override | ||
| public void put(final Phi phi) { | ||
| this.cached.set(null); | ||
| this.original.put(phi); | ||
|
Comment on lines
68
to
70
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Synchronize cache invalidation with initialization.
🔒 Proposed fix: serialize `put()` with `get()` initialization `@Override`
public void put(final Phi phi) {
- this.cached.set(null);
- this.original.put(phi);
+ this.lock.lock();
+ try {
+ this.cached.set(null);
+ this.original.put(phi);
+ } finally {
+ this.lock.unlock();
+ }
}🤖 Prompt for AI Agents |
||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,12 @@ | |
| */ | ||
| package org.eolang; | ||
|
|
||
| import java.util.Set; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import java.util.concurrent.CountDownLatch; | ||
| import java.util.concurrent.ExecutorService; | ||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.TimeUnit; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Surface worker failures and assert identity directly.
🧪 Proposed fix: collect futures and assert `sameInstance` for every result+import java.util.ArrayList;
+import java.util.List;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
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;
@@
`@Test`
- void returnsSameInstanceToConcurrentCallers() throws InterruptedException {
+ void returnsSameInstanceToConcurrentCallers() throws Exception {
final int threads = 16;
final Attr attr = new AtWithRho(
new AtComposite(new PhDefault(), phi -> phi),
new PhDefault()
);
- final Set<Phi> results = ConcurrentHashMap.newKeySet();
final CountDownLatch start = new CountDownLatch(1);
- final CountDownLatch done = new CountDownLatch(threads);
final ExecutorService pool = Executors.newFixedThreadPool(threads);
+ final List<Future<Phi>> futures = new ArrayList<>(threads);
try {
for (int idx = 0; idx < threads; ++idx) {
- pool.submit(() -> {
- try {
- start.await();
- results.add(attr.get());
- } catch (final InterruptedException ex) {
- Thread.currentThread().interrupt();
- } finally {
- done.countDown();
- }
+ futures.add(pool.submit(() -> {
+ start.await();
+ return attr.get();
});
}
start.countDown();
+ final Phi first = futures.get(0).get(10L, TimeUnit.SECONDS);
+ for (final Future<Phi> future : futures) {
+ MatcherAssert.assertThat(
+ "AtWithRho.get() must return the same instance for all concurrent callers",
+ future.get(10L, TimeUnit.SECONDS),
+ Matchers.sameInstance(first)
+ );
+ }
- MatcherAssert.assertThat(
- "all threads must finish",
- done.await(10L, TimeUnit.SECONDS),
- Matchers.is(true)
- );
} finally {
pool.shutdownNow();
}
- MatcherAssert.assertThat(
- "AtWithRho.get() must return the same instance for all concurrent callers",
- results,
- Matchers.hasSize(1)
- );
}Also applies to: 107-145 🤖 Prompt for AI Agents |
||
| import org.hamcrest.MatcherAssert; | ||
| import org.hamcrest.Matchers; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
@@ -97,4 +103,44 @@ void copiesWithNewRhoMustCallCopyOnOriginal() { | |
| Matchers.not(Matchers.is(obj)) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void returnsSameInstanceToConcurrentCallers() throws InterruptedException { | ||
| final int threads = 16; | ||
| final Attr attr = new AtWithRho( | ||
| new AtComposite(new PhDefault(), phi -> phi), | ||
| new PhDefault() | ||
| ); | ||
| final Set<Phi> results = ConcurrentHashMap.newKeySet(); | ||
| final CountDownLatch start = new CountDownLatch(1); | ||
| final CountDownLatch done = new CountDownLatch(threads); | ||
| final ExecutorService pool = Executors.newFixedThreadPool(threads); | ||
| try { | ||
| for (int idx = 0; idx < threads; ++idx) { | ||
| pool.submit(() -> { | ||
| try { | ||
| start.await(); | ||
| results.add(attr.get()); | ||
| } catch (final InterruptedException ex) { | ||
| Thread.currentThread().interrupt(); | ||
| } finally { | ||
| done.countDown(); | ||
| } | ||
| }); | ||
| } | ||
| start.countDown(); | ||
| MatcherAssert.assertThat( | ||
| "all threads must finish", | ||
| done.await(10L, TimeUnit.SECONDS), | ||
| Matchers.is(true) | ||
| ); | ||
| } finally { | ||
| pool.shutdownNow(); | ||
| } | ||
| MatcherAssert.assertThat( | ||
| "AtWithRho.get() must return the same instance for all concurrent callers", | ||
| results, | ||
| Matchers.hasSize(1) | ||
| ); | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.