Could use some pointers with this implementation

Status
Not open for further replies.
Hey all...

We receive a data feed in the form of formatted text-files exported from the source's database and securely copied to our local systems. Normally, we receive a file every five minutes, but sometimes the feed stalls and dumps several files in 30 minute intervals.

A 3rd party pre-processor breaks when reading more than 50 or so of these records at a time, so we have to segment the input into smaller chunks. Also, if the feed stalls, we want to push the data through after a given timeout regardless of whether we've reached the limit.

Finally, since there's no way for a process to determine that I'm through writing a file so that it knows that its ready for reading, we use a write-to-temp-file, close-then-rename-to-real-file "semaphore" so that when the file is complete, the file is renamed to its final form and a file reader can then just use the appropriate file name mask to grab files for input.

So, to that end, I've written this Java class that I call RollingFileWriter.

Purpose:
- Limit the number of "things"/records written to a file to a programmer-requested maximum and automatically close, rename and switch to a new file
- Force a switch if we haven't written a record in a programmer-requested maximum timeout

Here's the code (note, I transcribed from a private network, so I may have fat-fingered something):
Code:
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.logging.*;

public class RollingFileWriter implements Closeable {

  // public class constants
  public static final long DEFAULT_SWITCH_TIMEOUT_MS = 5 * 60 * 1000;  // 5 minutes
  public static final int DEFAULT_MAX_WRITES = 50;

  // private class constants
  private static final Logger LOG = Logger.getLogger(RollingFileWriter.class.getName());

  // private instance constants
  private final String outputFileMask;
  private final File outputDirectory;
  private final int maxWritesPerFile;
  private final long autoSwitchTimeout;
  private final Timer timer = new Timer("RollTaskPollTimer", true);

  // private instance variables
  private volatile long timerExpiry = -1;
  private volatile File currentFile;
  private volatile FileWriter writer;
  private volatile int writeCount;

  public RollingFileWriter(String fileMask, File outputDir, int maxWrites, long switchTimeout) {
    this.outputFileMask = fileMask;
    this.outputDirectory = outputDir;
    this.maxWritesPerFile = maxFiles;
    this.autoSwitchTimeout = switchTimeout;
    time.schedule(new AutoSwitchTask(), 5, 1000); // run the rolltask checker every second
    resetTimer();
  }

  @Override
  public void close() throws IOException {
    closeAndRename();
    timer.cancel();
  }

  public void write(Object o) throws IOException {
    if (writer == null) {
      startNewFile();
    }
    writer.write(o.toString());
    resetTimer();
    writeCount++;
    if (writeCountExceeded()) {
      closeAndRename();
    }
  }

  private void closeAndRename() {
    if (writer == null) {
      return;  // bail out as there's nothing to do
    }

    writer.close();
    writer = null;

    if (writeCount == 0) {
      // if we didn't write the the temp file, just delete it
      boolean success = currentFile.delete();
      if (!success) {
        LOG.log(Level.WARNING, "unable to delete file {0}", currentFile);
      }
      return;
    }

    String nextFileName = nextFilenameFromMask();
    File nextFile = new File(outputDirectory, nextFileName);
    while (nextFile.exists()) {
      nextFileName = nextFilenameFromMask();
      nextFile = new File(outputDirectory, nextFileName);
    }

    boolean moveWasSuccessful = currentFile.renameTo(newFile);
    if (!moveWasSuccessful) {
      if (nextFile.exists()) {
        throw new IOException("could not rename " + currentFile.getName() + " to " + nextFile.getName() + ": file exists");
      } else {
        throw new IOException("could not rename " + currentFile.getName() + " to " + nextFile.getName());
      }
    }
  }

  private String nextFilenameFromMask() {
    String sb = outputFileMask;
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
    Date date = new Date();
    sb = sb.replace("{0}", dateTimeFormat.format(date));
    return sb;
  }

  private void resetFiler() {
    timerExpiry = System.currentTimeMillis() + autoSwitchTimeout;
  }

  private void startNewFile() throws IOException {
    currentFile = File.createTempFile("tmp", "===", outputDirectory);
    writer = new FileWriter(currentFile);
    writeCount = 0;
  }

  private boolean writeCountExceeded() {
    return writeCount >= maxWritesPerFile;
  }

  private class AutoSwitchTask extends TimerTask {

    @Override 
    public void run() {
      try {
        if (timerHasExpired()) {
          closeAndRename();
          resetTimer();
        }
      } catch (IOException e) {
        LOG.log(Level.SEVERE, "", e);
      }
    }

    public boolean timerHasExpired() {
      return System.currentTimeMillis() >= timerExpiry;
    }
  }
}

I know I have a synchronization issue between the timer and the normal "main" thread which uses "write" (and, technically "close") -- whenever I set the timeout to a really small value, main-line "write" switching and the timer switching can collide giving me a closed stream exception.

However, I'm not sure where to apply synchronization, but I don't just want to apply it everywhere...

Help me fix my code? Or is there an entirely better way to do this?
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Stop trying to be clever, you don't know low lock techniques (throwing volatile everywhere is not the right answer, it's almost always the wrong answer)

Put in a trivial lock object, do the simplest thing possible with it you think is right and come back with what you have.

You're doing file IO, a rarely contended lock is so trivial in comparison it's at least 6 orders of magnitude if you're using spinning rust, and still 3 if you're on a fast SSD.
 

chalex

Ars Legatus Legionis
11,918
Subscriptor++
I guess I don't understand why any "code" is involved at all, why not just have a cron job or similar run every minute and break up the incoming records into individual files, with one record per file and then have the processing rename the files after they're processed?

I guess there are some kind of weird details about "stalled feeds"?
 
Status
Not open for further replies.