# Ownership and cleanup

Source: https://libtmux.org/en/java/latest/topics/context-managers/

> Scope-based cleanup for tmux objects, and when your program must kill them explicitly.

A tmux session, window, or pane normally remains until you kill it. Scope-based
cleanup can kill it when your code leaves a block, including after an exception.
See [Workspaces](https://libtmux.org/en/java/latest/concepts/workspaces/) for a temporary layout example.

<a id="java-server-is-closeable-but-closing-one-doesnt-kill-it"></a>

## Closing a server connection

Java's [`Server`](<https://libtmux.org/en/java/latest/reference/io-github-libtmux-server-server/>) implements [`AutoCloseable`](<https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/AutoCloseable.html>). Exiting `try (Server server =
Server.open(config))` releases the owned transport while tmux and its sessions
remain running. Kill sessions, windows, panes, or the server explicitly when
your program owns their cleanup.

```java
ServerConfig config = ServerConfig.builder()
        .endpoint(ServerEndpoint.socketPath(socket))
        .build();

try (Server server = Server.open(config)) {
    Session session = server.newSession("demo");
    Window window = session.newWindow("build");
    Pane pane = window.split();

    pane.sendLine("echo hello from libtmux");
    // session, window, and pane all outlive this block: only the
    // connection this `server` handle held is released on the way out.
}
```

<a id="what-this-means-in-practice"></a>

## Testing cleanup

Use explicit cleanup for objects whose handles have no disposal hook. For an
entire disposable test server, prefer your port's test fixture or server guard;
see [Testing with libtmux](https://libtmux.org/en/java/latest/guides/testing-with-libtmux/).
