seems liek something to work on ey, I need to git dough
[packetlaptime.git] / LogThread.java
blob38d2b38cbc9f03f81c7b1f4a2a924f0dcf86b498
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 log();
37 try {
38 out.close();
40 catch (IOException e) {
41 System.err.println(e);
45 /**
46 * Sets the startTime fields of this Node.
47 * The startTime field is used by the logging
48 * Node's LogThread to calculate average lap times.
50 * @param long The startTime of the Node.
52 public void setStartTime(long startTime) {
53 this.startTime = startTime;
56 public void log() {
57 try {
58 out.write("Average time for a packet to circle the ring: " +
59 (System.nanoTime() -
60 startTime)/(double)node.getSentPackets() +
61 " ms\n");
63 catch (IOException e) {
64 System.out.println(e);
68 public void run() {
69 while (keepLogging) {
70 try {
71 out.write("Average time for a packet to circle the ring: " +
72 (System.nanoTime() - startTime)/(double)node.getSentPackets() + " ms\n");
74 catch (IOException e) {
75 System.out.println(e);
77 try {
78 // sleep for a bit before writing
79 // the next average lap time (so not
80 // to fill the log file too much)
81 this.sleep(SLEEPTIME);
83 catch (InterruptedException e) {
84 System.out.println(e);
87 try {
88 out.close();
90 catch (IOException e) {
91 System.out.println(e);