Class Lifecycle.IOValue<T>

Type Parameters:
T - the value type
All Implemented Interfaces:
Lifecycle.ExtendedCloseable<IOException>, Closeable, AutoCloseable, Supplier<T>
Enclosing class:

public static final class Lifecycle.IOValue<T> extends Lifecycle.Value<T,IOException> implements Closeable
This class represents a closeable value. It is useful in cases where the object value doesn't implement the AutoCloseable interface but needs some cleanup work to do after usage. In the following example the created file is automatically deleted when leaving the try block.
// Create the closeable file. final IOValue<Path> file = new IOValue<>( Files.createFile(Path.of("some_file")), Files::deleteIfExists ); // Automatically delete the file after the test. try (file) { Files.write(file.get(), "foo".getBytes()); final var writtenText = Files.readString(file.get()); assert "foo".equals(writtenText); }
  • Constructor Details

    • IOValue

      public IOValue(T value, Lifecycle.ThrowingConsumer<? super T,? extends IOException> release)
      Create a new closeable value with the given resource value and its release method.
      value - the actual resource value
      release - the release method for the given value
      NullPointerException - if the release function is null
    • IOValue

      public IOValue(Lifecycle.ThrowingFunction<? super Lifecycle.IOResources,? extends T,? extends BE> builder) throws BE
      Opens a kind of try-catch with resources block. The difference is, that the resources, registered with the Lifecycle.Resources.add(Object, ThrowingConsumer) method, are only closed in the case of an error. If the value could be created, the caller is responsible for closing the opened resources by calling the Lifecycle.Value.close() method.
      final IOValue<Stream<Object>> result = new IOValue<>(resources -> { final var fin = resources.add(new FileInputStream(file.toFile())); final var bin = resources.add(new BufferedInputStream(fin)); final var oin = resources.add(new ObjectInputStream(bin)); return Stream.generate(() -> readNextObject(oin)) .takeWhile(Objects::nonNull); }); try (result) { result.get().forEach(System.out::println); }
      Type Parameters:
      BE - the exception type which might be thrown while building the value
      builder - the builder method
      BE - in the case of an error. If this exception is thrown, all already registered resources are closed.
      NullPointerException - if the given builder is null
      See Also: