Fwd: AutoCloseable blocking or not

Vitaly Davidovich vitalyd at gmail.com
Fri Oct 5 13:22:51 UTC 2012


Personally, if an API just had close() I'd expect that when it returns the
semantics of close are done.  If the resource may take a while to close
(whatever "a while" means in the context) I'd expect to have a closeAsync()
(or something akin to that) that returns a future or takes a callback to
execute when it's finished.

Sent from my phone
On Oct 5, 2012 9:15 AM, "Kasper Nielsen" <kasperni at gmail.com> wrote:

> On Fri, Oct 5, 2012 at 1:10 PM, David Holmes <david.holmes at oracle.com>
> wrote:
> > On 5/10/2012 7:56 PM, Alan Bateman wrote:
> >>
> >>
> >> Forwarding Kasper's mail to the right list.
> >>
> >> From: Kasper Nielsen <kasperni at gmail.com>
> >> To: nio-discuss at openjdk.java.net
> >>
> >> I have a question about the AutoCloseable interface. Since I cannot
> >> find any mention about how asynchronously closeable resources should
> >> be handled.
> >>
> >> Say I wanted juc.ThreadPoolExecutorService to implement AutoCloseable.
> >> When close() returned should the executor be in the shutdown phase or
> >> in the terminated phase?
> >>
> >> In other words should I implement close() like this (which I believe)
> >>
> >> public void close() {
> >> executor.shutdown();
> >> executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); //ignore
> >> any interrupted exceptions
> >> }
> >>
> >> or like this
> >>
> >> public void close() {
> >> executor.shutdown();
> >> }
> >
> >
> > That's really an arbitrary choice. What semantics do you want the
> close() to
> > have?
>
> The least surprising from a user perspective.
>
> If a given auto closable resource can be in 3 states: running ->
> closing -> closed.
> And I have a resource where the closing phase can take multiple seconds.
> Would the user assume that when close() returned, the resource was in
> the closed state.
> Or could I just spawn a thread that did the actual close and
> immediately return control to the caller with the resource in the
> closing state.
>
> Given that any class I could find in the JDK that implements
> AutoCloseable blocks until the socket/filesystem/rowset/... is fully
> closed.
> I thought maybe using AutoCloseable was a bit of a stretch to use for
> closing a resource asynchronously.
>
> - Kasper
>
> >
> > Personally I don't think AutoCloseable is a good fit for an executor
> service
> > as the lifetime of an autocloseable is tied to a block of code and that
> > would be a rare usage for an executor service.
>
> I agree, I was just using the executor service as a rather poor example.
>
> Kasper
>



More information about the core-libs-dev mailing list