2 Replies Latest reply: Nov 22, 2006 11:18 AM by 807607 RSS

    FileWriter synchronization problem?

    807607
      Why would timestamps logged get out of sequence occasionally using code like this:

      public class logger {
      private FileWriter fw;
      private int count = 0;
      ...
      public synchronized void printLog(String message) {
      String time = getTime();
      fw.write(time + " " + message + " count " + ++count + "\n");
      fw.flush();
      }
      private static String getTime() {
      Calendar now = Calendar.getInstance();
      ...
      }
      }

      One logger shared by several threads calling the printLog method. Synchronized on fw does make any difference, neither does making getTime() not-static.

      The problem is probably somewhere else, but how could the timestamps get out of order when the count is in order?

      Thanks for pointers.

      w4j