Java Reference
In-Depth Information
This class, its interfaces, and a demonstration of its call are all given in Listing 7-4. The class
implementation itself is rather ugly. This is because there are a lot of type variables and strange syntax
floating around, and it is made worse by the fact that interfaces cannot be members of classes: they are
always static. However, the resulting API and usage is actually quite nice.
Listing 7-4. Handling Resources with an Object Using Optional
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;
import java.util.stream.*;
public class Listing4 {
public static class ResourceExceptionHandler
<RESOURCE_T extends AutoCloseable>
{
public static interface FunctionWithResource
<RESOURCE_T extends AutoCloseable, IN_T, OUT_T>
{
OUT_T apply(RESOURCE_T resource, IN_T value) throws Exception;
}
public static interface ResourceMaker
<RESOURCE_T extends AutoCloseable>
{
RESOURCE_T create() throws Exception;
}
private final ResourceMaker<RESOURCE_T> init;
private final ConcurrentMap<Object, Exception> exceptions =
new ConcurrentSkipListMap<>();
public ResourceExceptionHandler(final ResourceMaker<RESOURCE_T> init) {
Objects.requireNonNull(init,
"ResourceMaker (initialization code for resource)");
this.init = init;
}
public Map<Object, Exception> getExceptions() {
return exceptions;
}
Search WWH ::




Custom Search