CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-eclipse-jetty--jetty-util

Comprehensive Java utility library providing infrastructure and helper classes for the Eclipse Jetty web server

Pending
Overview
Eval results
Files

component-lifecycle.mddocs/

Component Lifecycle

Robust component lifecycle management with container support, event notifications, and graceful shutdown capabilities. The lifecycle system provides consistent state management for all Jetty components.

Capabilities

LifeCycle Interface

Core component lifecycle management interface with well-defined state transitions.

/**
 * Component lifecycle interface
 */
public interface LifeCycle {
    /** Start the component */
    void start() throws Exception;
    
    /** Stop the component */
    void stop() throws Exception;
    
    /** Check if component is running */
    boolean isRunning();
    
    /** Check if component is started */
    boolean isStarted();
    
    /** Check if component is stopped */
    boolean isStopped();
    
    /** Check if component is failed */
    boolean isFailed();
    
    /** Check if component is starting */
    boolean isStarting();
    
    /** Check if component is stopping */
    boolean isStopping();
    
    /** Add lifecycle listener */
    void addLifeCycleListener(LifeCycle.Listener listener);
    
    /** Remove lifecycle listener */
    void removeLifeCycleListener(LifeCycle.Listener listener);
    
    /** Lifecycle event listener interface */
    interface Listener {
        default void lifeCycleStarting(LifeCycle event) {}
        default void lifeCycleStarted(LifeCycle event) {}
        default void lifeCycleFailure(LifeCycle event, Throwable cause) {}
        default void lifeCycleStopping(LifeCycle event) {}
        default void lifeCycleStopped(LifeCycle event) {}
    }
}

Usage Examples:

import org.eclipse.jetty.util.component.LifeCycle;

// Basic lifecycle usage
LifeCycle component = new MyComponent();

// Add listener for lifecycle events
component.addLifeCycleListener(new LifeCycle.Listener() {
    @Override
    public void lifeCycleStarted(LifeCycle event) {
        System.out.println("Component started: " + event);
    }
    
    @Override
    public void lifeCycleFailure(LifeCycle event, Throwable cause) {
        System.err.println("Component failed: " + cause.getMessage());
    }
});

// Start and stop
try {
    component.start();
    // ... use component
} finally {
    component.stop();
}

AbstractLifeCycle

Base implementation providing common lifecycle functionality.

/**
 * Abstract base class for lifecycle components
 */
public abstract class AbstractLifeCycle implements LifeCycle {
    /** Get current lifecycle state */
    public State getState();
    
    /** Template method for start implementation */
    protected abstract void doStart() throws Exception;
    
    /** Template method for stop implementation */
    protected abstract void doStop() throws Exception;
    
    /** Set state to failed */
    protected void setFailed(Throwable th);
    
    /** Lifecycle states */
    public enum State {
        STOPPED, STARTING, STARTED, STOPPING, FAILED
    }
}

Usage Examples:

import org.eclipse.jetty.util.component.AbstractLifeCycle;

public class MyService extends AbstractLifeCycle {
    private ServerSocket serverSocket;
    
    @Override
    protected void doStart() throws Exception {
        serverSocket = new ServerSocket(8080);
        System.out.println("Service started on port 8080");
    }
    
    @Override
    protected void doStop() throws Exception {
        if (serverSocket != null) {
            serverSocket.close();
            serverSocket = null;
        }
        System.out.println("Service stopped");
    }
    
    public void handleClient() {
        if (!isStarted()) {
            throw new IllegalStateException("Service not started");
        }
        // Handle client request
    }
}

Container Interface

Component containment and relationship management.

/**
 * Container interface for managing child components
 */
public interface Container {
    /** Add a bean to the container */
    void addBean(Object bean);
    
    /** Add a bean with managed lifecycle */
    void addBean(Object bean, boolean managed);
    
    /** Remove a bean from the container */
    boolean removeBean(Object bean);
    
    /** Get all beans of specified type */
    <T> Collection<T> getBeans(Class<T> clazz);
    
    /** Get single bean of specified type */
    <T> T getBean(Class<T> clazz);
    
    /** Check if bean is managed */
    boolean isManaged(Object bean);
    
    /** Container event listener */
    interface Listener {
        void beanAdded(Container parent, Object child);
        void beanRemoved(Container parent, Object child);
    }
    
    /** Inherited listener that propagates to children */
    interface InheritedListener extends Listener {
        // Marker interface for listeners that should be inherited by child containers
    }
}

ContainerLifeCycle

Combined lifecycle and container implementation.

/**
 * Lifecycle implementation with container capabilities
 */
public class ContainerLifeCycle extends AbstractLifeCycle implements Container, Dumpable {
    /** Add managed bean */
    public void addManaged(LifeCycle bean);
    
    /** Install bean (add and start if container is started) */
    public void installBean(Object bean);
    
    /** Install bean with management flag */
    public void installBean(Object bean, boolean managed);
    
    /** Uninstall bean (stop and remove if managed) */
    public void uninstallBean(Object bean);
    
    /** Update bean (replace existing) */
    public void updateBean(Object oldBean, Object newBean);
    
    /** Get contained beans */
    public Collection<Object> getBeans();
    
    /** Auto start/stop child components */
    public void setAutoStart(boolean auto);
    
    /** Check if auto start is enabled */
    public boolean isAutoStart();
}

Usage Examples:

import org.eclipse.jetty.util.component.ContainerLifeCycle;

public class Server extends ContainerLifeCycle {
    private final List<Handler> handlers = new ArrayList<>();
    
    public void addHandler(Handler handler) {
        addBean(handler, true); // Managed lifecycle
        handlers.add(handler);
    }
    
    public void removeHandler(Handler handler) {
        removeBean(handler);
        handlers.remove(handler);
    }
    
    @Override
    protected void doStart() throws Exception {
        // Start all managed beans automatically
        super.doStart();
        System.out.println("Server started with " + getBeans(Handler.class).size() + " handlers");
    }
    
    @Override
    protected void doStop() throws Exception {
        System.out.println("Stopping server");
        // Stop all managed beans automatically
        super.doStop();
    }
}

Graceful Shutdown

Graceful shutdown interface for components that need time to complete operations.

/**
 * Interface for components supporting graceful shutdown
 */
public interface Graceful {
    /** Initiate graceful shutdown */
    CompletableFuture<Void> shutdown();
    
    /** Check if shutdown is in progress */
    boolean isShutdown();
    
    /** Graceful shutdown utility */
    static CompletableFuture<Void> shutdown(Object... objects) {
        // Utility method to shutdown multiple objects
    }
}

Usage Examples:

import org.eclipse.jetty.util.component.Graceful;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class GracefulService extends ContainerLifeCycle implements Graceful {
    private volatile boolean shuttingDown = false;
    private final AtomicInteger activeRequests = new AtomicInteger();
    
    @Override
    public CompletableFuture<Void> shutdown() {
        shuttingDown = true;
        
        return CompletableFuture.runAsync(() -> {
            // Wait for active requests to complete
            while (activeRequests.get() > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        });
    }
    
    @Override
    public boolean isShutdown() {
        return shuttingDown;
    }
    
    public void handleRequest() {
        if (shuttingDown) {
            throw new IllegalStateException("Service is shutting down");
        }
        
        activeRequests.incrementAndGet();
        try {
            // Process request
        } finally {
            activeRequests.decrementAndGet();
        }
    }
}

// Usage
GracefulService service = new GracefulService();
service.start();

// Later, shutdown gracefully
CompletableFuture<Void> shutdown = service.shutdown();
try {
    shutdown.get(30, TimeUnit.SECONDS); // Wait up to 30 seconds
    service.stop();
} catch (TimeoutException e) {
    // Force stop if graceful shutdown times out
    service.stop();
}

Utility Classes

Additional lifecycle utilities and helpers.

/**
 * Lifecycle utilities
 */
public class LifeCycleCallbackCollection<T> implements LifeCycle.Listener {
    /** Add callback for specific event */
    public void addCallback(T callback);
    
    /** Remove callback */
    public void removeCallback(T callback);
}

/**
 * File-based lifecycle notifications
 */
public class FileNoticeLifeCycleListener implements LifeCycle.Listener {
    /** Create listener that writes to file on events */
    public FileNoticeLifeCycleListener(Path noticeFile, String startedMessage, String stoppedMessage);
}

/**
 * JVM halt on lifecycle failure
 */
public class HaltLifeCycleListener implements LifeCycle.Listener {
    /** Create listener that halts JVM on failure */
    public HaltLifeCycleListener();
    
    /** Create listener with custom exit code */
    public HaltLifeCycleListener(int exitCode);
}

Usage Examples:

import org.eclipse.jetty.util.component.*;
import java.nio.file.Paths;

// File-based notifications
FileNoticeLifeCycleListener fileListener = new FileNoticeLifeCycleListener(
    Paths.get("/var/run/myapp.status"),
    "STARTED",
    "STOPPED"
);
component.addLifeCycleListener(fileListener);

// JVM halt on failure (for critical services)
HaltLifeCycleListener haltListener = new HaltLifeCycleListener(1);
criticalService.addLifeCycleListener(haltListener);

Lifecycle Patterns

Template Method Pattern

// Extend AbstractLifeCycle for consistent behavior
public class MyComponent extends AbstractLifeCycle {
    @Override
    protected void doStart() throws Exception {
        // Initialize resources
        // Will be called exactly once during start transition
    }
    
    @Override
    protected void doStop() throws Exception {
        // Cleanup resources
        // Will be called exactly once during stop transition
    }
}

Container Pattern

// Use ContainerLifeCycle for components with children
public class CompositeService extends ContainerLifeCycle {
    public CompositeService() {
        addBean(new DatabaseService(), true); // Managed
        addBean(new CacheService(), true);    // Managed
        addBean(new Logger(), false);         // Unmanaged
    }
    
    // Child components automatically started/stopped
}

Error Handling

Lifecycle operations handle errors through:

  • State transitions to FAILED on exceptions during start/stop
  • Listener notifications for failure events
  • Automatic cleanup of partially started components
  • Exception propagation to callers

Best Practices

  1. Always extend AbstractLifeCycle for consistent behavior
  2. Use ContainerLifeCycle for components with dependencies
  3. Implement Graceful for services that handle requests
  4. Add lifecycle listeners for monitoring and diagnostics
  5. Handle exceptions in doStart/doStop methods appropriately
  6. Use managed beans for automatic lifecycle propagation
  7. Test state transitions thoroughly in component tests

Install with Tessl CLI

npx tessl i tessl/maven-org-eclipse-jetty--jetty-util

docs

async-operations.md

component-lifecycle.md

core-utilities.md

data-structures.md

index.md

resource-management.md

security.md

statistics.md

threading.md

tile.json