Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reentrant lock #1689

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 12 additions & 16 deletions src/main/java/org/cactoos/scalar/Synced.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
package org.cactoos.scalar;

import org.cactoos.Scalar;
import java.util.concurrent.locks.ReentrantLock;

/**
* Scalar that is thread-safe.
Expand All @@ -50,37 +51,32 @@
public final class Synced<T> implements Scalar<T> {

/**
* The scalar to cache.
*/
private final Scalar<? extends T> origin;

/**
* Sync lock.
* The lock.
*/
private final Object mutex;
private final ReentrantLock lock;

/**
* Ctor.
* @param src The Scalar to cache
* The scalar to cache.
*/
public Synced(final Scalar<? extends T> src) {
this(src, src);
}
private final Scalar<? extends T> origin;

/**
* Ctor.
*
* @param scalar The Scalar to cache
* @param lock Sync lock
*/
public Synced(final Scalar<? extends T> scalar, final Object lock) {
public Synced(final Scalar<? extends T> scalar) {
this.origin = scalar;
this.mutex = lock;
this.lock = new ReentrantLock();
}

@Override
public T value() throws Exception {
synchronized (this.mutex) {
this.lock.lock();
try {
return this.origin.value();
} finally {
this.lock.unlock();
}
}
}
12 changes: 2 additions & 10 deletions src/main/java/org/cactoos/text/Synced.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,12 @@
* @since 0.18
*/
public final class Synced extends TextEnvelope {
/**
* Ctor.
* @param text The text
*/
public Synced(final Text text) {
this(text, text);
}

/**
* Ctor.
* @param text The text
* @param lck The lock
*/
public Synced(final Text text, final Object lck) {
super(new TextOf(new org.cactoos.scalar.Synced<>(text::asString, lck)));
public Synced(final Text text) {
super(new TextOf(new org.cactoos.scalar.Synced<>(text::asString)));
}
}