Skip to content

Commit

Permalink
#12: introduced Memory::dispose
Browse files Browse the repository at this point in the history
  • Loading branch information
skapral committed Mar 23, 2022
1 parent fcd566b commit 24bdd2c
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.FutureTask;

Expand Down Expand Up @@ -75,6 +76,19 @@ public final <T> T memoized(MemoizedCallable<T> callable) {
}
}

@Override
public final <T> Optional<T> dispose(MemoizedCallable<T> callable) {
return Optional.ofNullable(memoizedObjects.remove(callable))
.map(futureTask -> {
try {
return futureTask.get();
} catch(Exception ex) {
throw new RuntimeException(ex);
}
})
.map(v -> (T) v);
}

@Override
public final void clean() {
memoizedObjects.clear();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
*/
package com.pragmaticobjects.oo.memoized.core;

import java.util.Optional;

/**
* Abstraction for a place where memoized values are kept.
*
Expand All @@ -39,6 +41,15 @@ public interface Memory {
*/
<T> T memoized(MemoizedCallable<T> callable);

/**
* Dispose memoized value, if anything was calculated, and return it to the caller
*
* @param <T> result type
* @param callable callable to memoize
* @return result
*/
<T> Optional<T> dispose(MemoizedCallable<T> callable);

/**
* Drop all memoized values
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import com.pragmaticobjects.oo.tests.TestCase;
import com.pragmaticobjects.oo.tests.junit5.TestsSuite;

import java.util.Optional;

/**
* Test {@link Memory} implementation that memoises nothing
*/
Expand All @@ -38,6 +40,11 @@ public final <T> T memoized(MemoizedCallable<T> callable) {
return callable.call();
}

@Override
public final <T> Optional<T> dispose(MemoizedCallable<T> callable) {
return Optional.empty();
}

@Override
public final void clean() {
// Do Nothing
Expand Down

0 comments on commit 24bdd2c

Please sign in to comment.