01 /**
02 *
03 * All content copyright (c) 2003-2008 Terracotta, Inc.,
04 * except as may otherwise be noted in a separate copyright notice.
05 * All rights reserved.
06 *
07 */
08 package demo.coordination;
09
10 import java.text.MessageFormat;
11 import java.util.logging.Logger;
12
13 import org.springframework.beans.factory.DisposableBean;
14 import org.springframework.beans.factory.InitializingBean;
15
16 /**
17 * Simple service using process coordination via synchronization.
18 *
19 *@author Terracotta, Inc.
20 */
21 public class CounterService
22 implements DisposableBean, InitializingBean, Runnable {
23
24 // By making this variables transient, Terracotta for Spring will *not* cluster it
25 private transient boolean running;
26
27 // These objects are distributed by Terracotta for Spring
28 private int counter = 0;
29 private final Object lock = new Object();
30 private static final Logger logger = Logger.getLogger(CounterService.class.getName());
31
32 private static final String LOG_PREFIX = System.getProperty("counter.log.prefix", "Counter service [INFO]:") + " ";
33 private static final int MAX_COUNTER = 999;
34 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}";
35
36 public String getStatus() {
37 synchronized (this) {
38 return MessageFormat.format(STATUS_FORMAT, new Object[]{running ? "active" : "passive", new Integer(counter)});
39 }
40 }
41
42 public void afterPropertiesSet()
43 throws Exception {
44 log("Creating background thread to try to increment counter");
45 Thread t = new Thread(this, "MessageService");
46 t.start();
47 }
48
49 public void destroy()
50 throws Exception {
51 running = false;
52 }
53
54 public void run() {
55 log("[background thread] Waiting to synchronize on the counter lock...");
56 synchronized (lock) {
57 log("[background thread] Got the counter lock, I will start incrementing the counter");
58 running = true;
59 boolean logFirstIncrement = true;
60 while (running) {
61 synchronized (this) {
62 counter++;
63 if (counter > MAX_COUNTER) {
64 counter = 0;
65 }
66 if (logFirstIncrement) {
67 log("[background thread] Incremented the counter to " + counter + " -- will increment every second");
68 logFirstIncrement = false;
69 }
70 }
71 try {
72 Thread.sleep(1000L);
73 }
74 catch (InterruptedException ex) {
75 // Ignore and keep processing
76 }
77 }
78 }
79 }
80
81 private static void log(String message) {
82 logger.info(LOG_PREFIX + message);
83 }
84
85 }
|