-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
51 additions
and
3 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package io.github.erdos.stencil.impl; | ||
|
||
import java.util.Objects; | ||
import java.util.concurrent.atomic.AtomicBoolean; | ||
import java.util.concurrent.locks.ReentrantReadWriteLock; | ||
import java.util.function.Supplier; | ||
|
||
public final class LifecycleLock implements AutoCloseable { | ||
|
||
private final ReentrantReadWriteLock lock; | ||
private final AtomicBoolean alive; | ||
private final Runnable cleanup; | ||
|
||
public LifecycleLock(Runnable cleanup) { | ||
this.lock = new ReentrantReadWriteLock(); | ||
this.alive = new AtomicBoolean(true); | ||
this.cleanup = Objects.requireNonNull(cleanup); | ||
} | ||
|
||
public <T> T run(Supplier<T> supplier) { | ||
lock.readLock().lock(); | ||
try { | ||
if (alive.get()) { | ||
return supplier.get(); | ||
} else { | ||
throw new IllegalStateException("Component has already been closed."); | ||
} | ||
} finally { | ||
lock.readLock().unlock(); | ||
} | ||
} | ||
|
||
@Override | ||
public void close() throws Exception { | ||
if (alive.get()) { | ||
lock.writeLock().lock(); | ||
try { | ||
if (alive.getAndSet(false)) { | ||
cleanup.run(); | ||
} | ||
} finally { | ||
lock.writeLock().unlock(); | ||
} | ||
} | ||
} | ||
} |
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
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