
net.codecrete.usb.common.ScopeCleanup Maven / Gradle / Ivy
//
// Java Does USB
// Copyright (c) 2022 Manuel Bleichenbacher
// Licensed under MIT License
// https://opensource.org/licenses/MIT
//
package net.codecrete.usb.common;
import java.util.ArrayList;
/**
* Auto closeable object for clean up actions.
*
*
* Multiple cleanup actions can be registered and will
* be executed when this object is closed. They are run
* in the reverse order they are registered.
*
*
* Use with {@code try (...)} clause:
*
*
* try (var cleanup = new ScopeCleanup()) {
* var service = ...;
* cleanup.add(() -> releaseService(service));
*
* ...more code...
* }
*
*/
public class ScopeCleanup implements AutoCloseable {
private final ArrayList cleanupActions = new ArrayList<>();
/**
* Registers a cleanup action to be run later.
*
* @param cleanupAction cleanup action
*/
public void add(Runnable cleanupAction) {
cleanupActions.add(cleanupAction);
}
@Override
public void close() {
var size = cleanupActions.size();
for (var i = size - 1; i >= 0; i--)
cleanupActions.get(i).run();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy