1 4 package demo.coordination; 5 6 import java.text.MessageFormat ; 7 import java.util.logging.Logger ; 8 9 import org.springframework.beans.factory.DisposableBean; 10 import org.springframework.beans.factory.InitializingBean; 11 12 15 public class CounterService 16 implements InitializingBean, DisposableBean, Runnable 17 { 18 private static final Logger logger = Logger.getLogger(CounterService.class.getName()); 19 20 private static final String LOG_PREFIX = System.getProperty("counter.log.prefix", "Counter service [INFO]:") + " "; 21 private static final int MAX_COUNTER = 999; 22 private static final String STATUS_FORMAT = "This node is currently <font color=\"green\"><b><i>{0}</i></b></font>.<br>The current distributed counter value is: {1}"; 23 24 private transient boolean running; 26 27 private int counter = 0; 29 private final Object lock = new Object (); 30 31 public void afterPropertiesSet() 32 throws Exception 33 { 34 log("Creating background thread to try to increment counter"); 35 Thread t = new Thread (this, "MessageService"); 36 t.start(); 37 } 38 39 public void destroy() 40 throws Exception 41 { 42 running = false; 43 } 44 45 public void run() 46 { 47 log("[background thread] Waiting to synchronize on the counter lock..."); 48 synchronized (lock) 49 { 50 log("[background thread] Got the counter lock, I will start incrementing the counter"); 51 running = true; 52 boolean logFirstIncrement = true; 53 while (running) 54 { 55 synchronized (this) 56 { 57 counter++; 58 if (counter > MAX_COUNTER) counter = 0; 59 if (logFirstIncrement) 60 { 61 log("[background thread] Incremented the counter to " + counter + " -- will increment every second"); 62 logFirstIncrement = false; 63 } 64 } 65 try 66 { 67 Thread.sleep(1000L); 68 } 69 catch (InterruptedException ex) 70 { 71 } 73 } 74 } 75 } 76 77 public String getStatus() 78 { 79 synchronized (this) 80 { 81 return MessageFormat.format(STATUS_FORMAT, new Object [] { running ? "active" : "passive", new Integer (counter) }); 82 } 83 } 84 85 private static void log(String message) 86 { 87 logger.info(LOG_PREFIX + message); 88 } 89 90 } 91 | Popular Tags |