compiles
[packetlaptime.git] / LogThread.java
blob589da6ca3ecb1180cba9fcd0a539f2211211cfd3
1 import java.util.*;
2 import java.io.*;
4 /**
5 * LogThread –
6 */
7 public class LogThread extends Thread {
9 // local fields
10 private final Node node;
11 private final String logFileName;
12 private boolean keepLogging = true;
13 private final int SLEEPTIME = 50;
14 private FileWriter file = null;
15 private BufferedWriter out = null;
16 private long startTime;
18 /**
19 * Constructs a new object of the LogThread class.
20 * This class writes out lap times of packets that
21 * circle the ring of UDP/TCP nodes.
23 public LogThread(Node node) {
24 this.node = node;
25 this.logFileName = "laptimes.log";
26 try {
27 this.file = new FileWriter(logFileName);
28 this.out = new BufferedWriter(file);
30 catch (IOException e) {
31 System.out.println(e);
35 public void end() {
36 this.keepLogging = false;
39 /**
40 * Sets the startTime fields of this Node.
41 * The startTime field is used by the logging
42 * Node's LogThread to calculate average lap times.
44 * @param long The startTime of the Node.
46 public void setStartTime(long startTime) {
47 this.startTime = startTime;
50 public void log() {
51 try {
52 out.write("Average time for a packet to circle the ring: " +
53 (System.nanoTime() -
54 startTime)/(double)node.getSentPackets() +
55 " ms\n");
57 catch (IOException e) {
58 System.out.println(e);
62 public void run() {
63 while (keepLogging) {
64 try {
65 out.write("Average time for a packet to circle the ring: " +
66 (System.nanoTime() - startTime)/(double)node.getSentPackets() + " ms\n");
68 catch (IOException e) {
69 System.out.println(e);
71 try {
72 // sleep for a bit before writing
73 // the next average lap time (so not
74 // to fill the log file too much)
75 this.sleep(SLEEPTIME);
77 catch (InterruptedException e) {
78 System.out.println(e);
81 try {
82 out.close();
84 catch (IOException e) {
85 System.out.println(e);