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.sharedqueue;
09
10 import java.util.Random;
11
12 /**
13 * Description of the Class
14 *
15 *@author Terracotta, Inc.
16 */
17 public class Job {
18
19 private final int duration;
20
21 private final String producer;
22
23 private Worker consumer;
24
25 private final int type;
26
27 private int state;
28
29 private String id;
30
31 private static final int STATE_READY = 0;
32
33 private static final int STATE_PROCESSING = 1;
34
35 private static final int STATE_COMPLETE = 2;
36
37 private static final int STATE_ABORTED = 3;
38
39 public Job(String producer, int id) {
40 Random random = new Random();
41 this.state = STATE_READY;
42 this.consumer = null;
43 this.producer = producer;
44 this.duration = random.nextInt(3) + 3;
45 this.type = random.nextInt(3) + 1;
46 this.id = Integer.toString(id);
47 while (this.id.length() < 3) {
48 this.id = "0" + this.id;
49 }
50 }
51
52 public final void run(Worker consumer) {
53 synchronized (this) {
54 this.state = STATE_PROCESSING;
55 this.consumer = consumer;
56 try {
57 Thread.sleep(duration * 1000L);
58 this.state = STATE_COMPLETE;
59 }
60 catch (InterruptedException ie) {
61 this.state = STATE_ABORTED;
62 }
63 }
64 }
65
66 public final String toXml() {
67 return "<job>" + "<id>" + id + "</id>" + "<type>" + type + "</type>"
68 + "<state>" + state + "</state>" + "<producer>" + producer
69 + "</producer>" + "<consumer>" + getConsumer() + "</consumer>"
70 + "<duration>" + duration + "</duration>" + "</job>";
71 }
72
73 private final String getConsumer() {
74 return consumer == null ? "" : consumer.getName();
75 }
76 }
|