Skip to content

Instantly share code, notes, and snippets.

@felixbarny
Created October 26, 2015 16:07
Show Gist options
  • Save felixbarny/6e5ae0b00f3370225651 to your computer and use it in GitHub Desktop.
Save felixbarny/6e5ae0b00f3370225651 to your computer and use it in GitHub Desktop.
package org.jstage.shop.commons.utils;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
public class BlockingAtomicReference<V> extends AtomicReference<V> {
private final CountDownLatch initialized = new CountDownLatch(1);
/**
* Initializes this reference with a value.
* <p/>
* If there where calls to {@link #blockingGet()} from other threads, these calls will return.
*
* @param value the initial value
*/
public void initialize(V value) {
set(value);
initialized.countDown();
}
/**
* Gets the current value, waiting until this reference got initialized via the {@link #initialize} method.
* <p/>
* After {@link #initialize} was called, this method behaves just like {@link #get}
*
* @return the current value
*/
public V blockingGet() throws InterruptedException {
initialized.await();
return get();
}
}
package org.jstage.shop.commons.utils;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class BlockingAtomicReferenceTest {
@Test
public void testBlockingGet() throws Exception {
final BlockingAtomicReference<Boolean> ref = new BlockingAtomicReference<>();
new Thread(() -> ref.initialize(true)).start();
assertTrue(ref.blockingGet());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment