Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.cactoos.Scalar;
- import org.cactoos.scalar.SyncScalar;
- import org.cactoos.scalar.True;
- import org.junit.Test;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.atomic.AtomicInteger;
- import java.util.concurrent.atomic.AtomicLong;
- public final class SyncTest {
- final class DoubleCheckScalar<T> implements Scalar<T> {
- private final Scalar<T> origin;
- private volatile T value;
- DoubleCheckScalar(Scalar<T> origin) {
- this.origin = origin;
- }
- @Override
- public T value() throws Exception {
- if (value == null) {
- synchronized (this) {
- if (value == null) {
- value = origin.value();
- }
- }
- }
- return value;
- }
- }
- @Test
- public void syncTest() throws Exception {
- final Scalar<Boolean> target = new SyncScalar<>(new True());
- final long time = test(target);
- System.out.printf("SyncScalar: %d ns\n", time);
- }
- @Test
- public void doubleCheckTest() throws Exception {
- final Scalar<Boolean> target = new DoubleCheckScalar<>(new True());
- final long time = test(target);
- System.out.printf("DoubleCheckScalar: %d ns\n", time);
- }
- /*
- * My results:
- * DoubleCheckScalar: 307_492_591 ns
- * SyncScalar: 2_045_077_027 ns
- */
- private static long test(Scalar<?> target) throws Exception {
- // warm up
- for (int i = 0; i < 1000; i++) {
- target.value();
- }
- final int iterations = 10_000_000;
- AtomicInteger pending = new AtomicInteger(iterations);
- final ExecutorService pool = Executors.newFixedThreadPool(20);
- //test
- AtomicLong sum = new AtomicLong();
- for (int i = 0; i < iterations; i++) {
- pool.submit(() -> {
- final long start = System.nanoTime();
- try {
- target.value();
- } catch (Exception e) {
- e.printStackTrace();
- }
- final long end = System.nanoTime();
- final long time = end - start;
- sum.addAndGet(time);
- pending.decrementAndGet();
- });
- }
- while (pending.get() > 0) {
- Thread.sleep(100);
- }
- pool.shutdown();
- return sum.get();
- }
- }
Add Comment
Please, Sign In to add comment