Skip to content

X Managed

Thomas Weißschuh edited this page Dec 20, 2018 · 4 revisions

Managed : functional resource management

Managed is the functional equivalent of an imperative try-catch-finally block in Java.

AutoCloseables

Create an instance of Managed with a resource to be used, make use of the specified resource via map or flatMap and resource closing is automatically managed for you (the flow and logic is similar to that of the JDK's Optional or a Stream with a single value, except that Managed focuses is on automatic resource management).

E.g. To manage an Autocloesable resource

Try<Data,Exception> result = Managed.of(autoCloseableResource)
                                    .map(resource->use(resource))
                                    .map(data->save(data));
                                    .run();

non-AutoCloseables

Managed can also automatically manage non-Autocloseable resources, the trick is to pass a Consumer that do the closing.

Managed.of(nonAutoCloseableResource,r->r.close())
       .map(resource->use(resource))
       .run();

A hibernate example

In the example below we can use Managed.of to manage the Hibernate Session resource. We can use the Session to delete data from our database, and we could also use the session to create and manage a transaction. The Managed::with operator allows us to create a new artefact from the managed resource - in this case to create a Transaction from the Managed Hibernate Session, and to use it along side the managed resource (this is syntax sugar that results in much cleaner code than passing a Tuple between Managed operations).

SessionFactory factory;

Try<String, Throwable> res = Managed.of(factory::openSession)
                                    .with(Session::beginTransaction)
                                    .map((session, tx) ->

                                            deleteFromMyTable(session)
                                              .bipeek(success -> tx.commit(),error -> tx.rollback())


                                    ).foldRun(Try::flatten);

Managed and IO

Managed can be leveraged from inside the cyclops IO monad, the bracket operator on IO manages the returned resource.

E.g. to read one line from a File

IO.of(this::getFile)
          .bracket(file -> new BufferedReader(new FileReader(file)))
          .map(reader -> reader.readLine());
          .run();

The bracket method ensures the Readers are correctly closed after use.

Clone this wiki locally