Created
October 26, 2015 16:07
-
-
Save felixbarny/6e5ae0b00f3370225651 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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