Mercurial Hosting > nabble
comparison 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 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:7ecd1a4ef557 |
---|---|
1 package nabble.model; | |
2 | |
3 import org.slf4j.Logger; | |
4 import org.slf4j.LoggerFactory; | |
5 | |
6 import java.util.Date; | |
7 | |
8 | |
9 public final class Batch { | |
10 | |
11 // use this logger from Runnable | |
12 public static final Logger logger = LoggerFactory.getLogger(Batch.class); | |
13 | |
14 private static final Object lock = new Object(); | |
15 private static Batch currentBatch = null; | |
16 | |
17 public static Batch currentBatch() { | |
18 synchronized(lock) { | |
19 return currentBatch; | |
20 } | |
21 } | |
22 | |
23 public static final class AlreadyRunningException extends Exception { | |
24 private AlreadyRunningException() { | |
25 super( "already running batch " + currentBatch.name ); | |
26 } | |
27 } | |
28 | |
29 private static final class StoppedException extends RuntimeException {} | |
30 | |
31 public final String name; | |
32 private final Runnable task; | |
33 private long startTime; | |
34 private volatile boolean isStopped = false; | |
35 | |
36 private Batch( final String name, final Runnable task ) { | |
37 this.name = name; | |
38 this.task = new Runnable(){public void run(){ | |
39 try { | |
40 logger.error( "batch " + name + " started" ); | |
41 startTime = System.currentTimeMillis(); | |
42 task.run(); | |
43 long after = System.currentTimeMillis(); | |
44 logger.error( "batch " + name + " done in " + (after - startTime) + " ms" ); | |
45 } catch(StoppedException e) { | |
46 logger.error( "batch " + name + " was stopped" ); | |
47 } catch(RuntimeException e) { | |
48 logger.error( "batch " + name + " failed", e ); | |
49 } finally { | |
50 synchronized(lock) { | |
51 currentBatch = null; | |
52 } | |
53 } | |
54 }}; | |
55 } | |
56 | |
57 public static void run( final String name, final Runnable task ) | |
58 throws AlreadyRunningException | |
59 { | |
60 synchronized(lock) { | |
61 if( currentBatch != null ) | |
62 throw new AlreadyRunningException(); | |
63 currentBatch = new Batch(name,task); | |
64 Executors.executeNow(currentBatch.task); | |
65 } | |
66 } | |
67 | |
68 public static void checkStopped() { | |
69 synchronized(lock) { | |
70 if( currentBatch!=null && currentBatch.isStopped ) | |
71 throw new StoppedException(); | |
72 } | |
73 } | |
74 | |
75 public void stop() { | |
76 isStopped = true; | |
77 } | |
78 | |
79 static void shutdown() { | |
80 synchronized(lock) { | |
81 if (currentBatch!=null) | |
82 currentBatch.stop(); | |
83 } | |
84 } | |
85 | |
86 public String toString() { | |
87 return "Batch - " + name + " started at " + new Date(startTime) + ", " + | |
88 (System.currentTimeMillis() - startTime) + " ms ago"; | |
89 } | |
90 } |