Mercurial Hosting > nabble
view src/nabble/model/Batch.java @ 62:4674ed7d56df default tip
remove n2
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Sat, 30 Sep 2023 20:25:29 -0600 |
parents | 7ecd1a4ef557 |
children |
line wrap: on
line source
package nabble.model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; public final class Batch { // use this logger from Runnable public static final Logger logger = LoggerFactory.getLogger(Batch.class); private static final Object lock = new Object(); private static Batch currentBatch = null; public static Batch currentBatch() { synchronized(lock) { return currentBatch; } } public static final class AlreadyRunningException extends Exception { private AlreadyRunningException() { super( "already running batch " + currentBatch.name ); } } private static final class StoppedException extends RuntimeException {} public final String name; private final Runnable task; private long startTime; private volatile boolean isStopped = false; private Batch( final String name, final Runnable task ) { this.name = name; this.task = new Runnable(){public void run(){ try { logger.error( "batch " + name + " started" ); startTime = System.currentTimeMillis(); task.run(); long after = System.currentTimeMillis(); logger.error( "batch " + name + " done in " + (after - startTime) + " ms" ); } catch(StoppedException e) { logger.error( "batch " + name + " was stopped" ); } catch(RuntimeException e) { logger.error( "batch " + name + " failed", e ); } finally { synchronized(lock) { currentBatch = null; } } }}; } public static void run( final String name, final Runnable task ) throws AlreadyRunningException { synchronized(lock) { if( currentBatch != null ) throw new AlreadyRunningException(); currentBatch = new Batch(name,task); Executors.executeNow(currentBatch.task); } } public static void checkStopped() { synchronized(lock) { if( currentBatch!=null && currentBatch.isStopped ) throw new StoppedException(); } } public void stop() { isStopped = true; } static void shutdown() { synchronized(lock) { if (currentBatch!=null) currentBatch.stop(); } } public String toString() { return "Batch - " + name + " started at " + new Date(startTime) + ", " + (System.currentTimeMillis() - startTime) + " ms ago"; } }