Skip to content

Commit

Permalink
Improve Lazy
Browse files Browse the repository at this point in the history
  • Loading branch information
minborg committed Dec 9, 2015
1 parent c023ad1 commit 38833db
Show file tree
Hide file tree
Showing 2 changed files with 139 additions and 12 deletions.
20 changes: 8 additions & 12 deletions src/main/java/com/speedment/internal/util/Lazy.java
Expand Up @@ -16,10 +16,12 @@
*/
package com.speedment.internal.util;

import static java.util.Objects.requireNonNull;
import java.util.function.Supplier;

/**
* Generic lazy initialization class.
* Generic lazy initialization class. The supplier must produce a non-null
* value.
*
* This class is thread safe. The Supplier is guaranteed to be called exactly
* one time following one or several calls to
Expand All @@ -32,22 +34,16 @@
public final class Lazy<T> {

private T value;
private boolean initializedFast;
private volatile boolean initializedVolatile;

public T getOrCompute(Supplier<T> supplier) {
if (!initializedFast) {
maybeCompute(supplier);
}
return value;
return value == null ? maybeCompute(supplier) : value;
}

private synchronized void maybeCompute(Supplier<T> supplier) {
if (!initializedVolatile) {
value = supplier.get();
initializedVolatile = true;
initializedFast = true;
private synchronized T maybeCompute(Supplier<T> supplier) {
if (value == null) {
value = requireNonNull(supplier.get());
}
return value;
}

}
131 changes: 131 additions & 0 deletions src/test/java/com/speedment/internal/util/LazyTest.java
@@ -0,0 +1,131 @@
/**
*
* Copyright (c) 2006-2015, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.speedment.internal.util;

import com.speedment.exception.SpeedmentException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
*
* @author pemi
*/
public class LazyTest {

private static final Integer ONE = 1;
private static final Integer TWO = 2;
private static final Supplier<Integer> ONE_SUPPLIER = () -> ONE;
private static final Supplier<Integer> TWO_SUPPLIER = () -> TWO;
private static final Supplier<Integer> NULL_SUPPLIER = () -> null;

Lazy<Integer> instance;

public LazyTest() {
}

@BeforeClass
public static void setUpClass() {
}

@AfterClass
public static void tearDownClass() {
}

@Before
public void setUp() {
instance = new Lazy<>();
}

@After
public void tearDown() {
}

@Test
public void testGetOrCompute() {
System.out.println("getOrCompute");
assertEquals(ONE, instance.getOrCompute(ONE_SUPPLIER));
assertEquals(ONE, instance.getOrCompute(TWO_SUPPLIER));
}

@Test(expected = NullPointerException.class)
public void testGetOrComputeSuppliedNull() {
System.out.println("testGetOrComputeSuppliedNull");
instance.getOrCompute(NULL_SUPPLIER);
}

@Test
public void testConcurrency() throws InterruptedException, ExecutionException {
System.out.println("testConcurrency");
final int threads = 8;
ExecutorService executorService = Executors.newFixedThreadPool(8);

for (int i = 0; i < 10000; i++) {
final Lazy<Long> lazy = new Lazy<>();
final Callable<Long> callable = () -> {
return lazy.getOrCompute(() -> Thread.currentThread().getId());
};
List<Future<Long>> futures
= IntStream.rangeClosed(0, threads)
.mapToObj($ -> executorService.submit(callable))
.collect(toList());

while (!futures.stream().allMatch(Future::isDone)) {
}

Set<Long> ids = futures.stream()
.map(LazyTest::getFutureValue)
.collect(toSet());

assertEquals("Failed at iteration " + i, 1, ids.size());

}

executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.SECONDS);

}

private static <T> T getFutureValue(Future<T> future) {
try {
return future.get();
} catch (ExecutionException | InterruptedException e) {
throw new SpeedmentException(e);
}
}

}

0 comments on commit 38833db

Please sign in to comment.