diff src/nabble/model/Batch.java @ 0:7ecd1a4ef557

add content
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 21 Mar 2019 19:15:52 -0600
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/nabble/model/Batch.java	Thu Mar 21 19:15:52 2019 -0600
@@ -0,0 +1,90 @@
+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";
+	}
+}