Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Spring make sure Closeable beans are closed in the correct order?

Tags:

java

spring

Let's pretend that we have two Closeable beans:

@Component
public class CloseableBean1 implements Closeable {

    private BufferedOutputStream outputStream;

    @Override
    public void close() throws IOException {
        try {
            outputStream.close();
        } catch (Exception e) {
            // ignore e
        }
    }
}


@Component
public class CloseableBean2 implements Closeable {    

    @Autowired
    private CloseableBean1 bean1;


    @Override
    public void close() throws IOException {
        try {
            bean1.close();
        } catch (Exception e) {
            // ignore e
        }
    }
}

Does Spring make sure that CloseableBean2 is closed first and then CloseableBean1 is closed?

like image 922
Behrang Avatar asked Mar 25 '16 11:03

Behrang


Video Answer


1 Answers

There is nothing specific in documentation about order of disposing, but... the description of depends-on we can see, that depends-on should be used only if bean does not explicitly depend on another. And there is noted, that dependent bean will always be destroyed first.

In your case bean CloseableBean2 always will be destroyed first, because it contains explicitly dependency of CloseableBean.


I would prefer to make additional protection. Something like:

@Component
public class CloseableBean1 implements Closeable {

    private boolean closed = false;

    @Override
    public void close() throws IOException {
        if(closed) return;   
        outputStream.close();
        closed=true;
    }
}

Official documentation recommend us:

...and to internally mark the Closeable as closed, prior to throwing the IOException.

This approach helps to avoid accidental repeated call of close() on already closed stream. But if exception will occurred during first invocation of close(), we will able to handle it.

like image 162
Ken Bekov Avatar answered Oct 10 '22 01:10

Ken Bekov