Skip to content

Commit

Permalink
yegor256#756 Turn SolidScalar faster
Browse files Browse the repository at this point in the history
  • Loading branch information
pbenety committed May 10, 2018
1 parent 0314515 commit 26fd17a
Showing 1 changed file with 24 additions and 10 deletions.
34 changes: 24 additions & 10 deletions src/main/java/org/cactoos/scalar/SolidScalar.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@
*/
package org.cactoos.scalar;

import org.cactoos.Func;
import org.cactoos.Scalar;
import org.cactoos.func.SolidFunc;

/**
* Cached and synchronized version of a Scalar.
Expand All @@ -42,22 +40,38 @@
public final class SolidScalar<T> implements Scalar<T> {

/**
* Func.
* Origin.
*/
private final Func<Boolean, T> func;
private final Scalar<T> origin;

/**
* Cache.
*/
private volatile T cache;

/**
* Sync lock.
*/
private final Object lock;

/**
* Ctor.
* @param scalar The Scalar to cache
* @param origin The Scalar to cache and sync
*/
public SolidScalar(final Scalar<T> scalar) {
this.func = new SolidFunc<>(
input -> scalar.value()
);
public SolidScalar(final Scalar<T> origin) {
this.origin = origin;
this.lock = new Object();
}

@Override
public T value() throws Exception {
return this.func.apply(true);
if (this.cache == null) {
synchronized (this.lock) {
if (this.cache == null) {
this.cache = this.origin.value();
}
}
}
return this.cache;
}
}

0 comments on commit 26fd17a

Please sign in to comment.