CP - Proposed Solution (Java -- The Meat)
This section addresses the specific functions from the Statement of Problem.
In this project, I have preferred Exception handling rather than return values from methods. This is merely a matter of taste, and alternative implementations could have employed return values over Exception handling.
For those who wish to read ahead, the full source files are Reader.java and Writer.java.
The Read Requirement
The first requirement is to be able to read from a log file. Each Reader is called with one CID, and the Reader must return only entries with that CID.
The enclosing loop below handles getting all entries from the logfile:
/**
* Sends the contents of the commit log to stdout. Note that
* it ignores all entries with CIDs different than the current
* CID for this reader.
*
* If it is successful, it returns silently.
*
* If it fails, it throws a RuntimeException, with the error
* set to the explanation of the failure.
*
* @return void
*/
public final void fetch() {
if(cid.length() < 1) {
throw new RuntimeException("Must set CID before logging entries.");
}
try {
synchronized(this) {
// Open our file reader
fileReader = new FileReader(fh);
br = new BufferedReader(fileReader);
String s;
line_cntr = 0;
while((s = br.readLine()) != null) {
String out = parseLine(s);
if(out != null) {
System.out.println(out);
}
line_cntr++;
}
}
} catch(IOException e) {
throw new RuntimeException(&quot;IO Error writing to log file [&quot;+fh.getPath()+&quot;] &quot;+e);
}
}</code></pre></figure>
Note that the synchronized block prevents multi-threading from interfering with any of the scarce or shared resources. Since there are no race conditions to worry about here, there is no semaphore use.
The block above uses another method to parse the line of text. That is implemented as:
/**
* Parses a single line from the log file, and displays
* it if the CID matches the current CID of this reader
*
* Note, this is NOT thread-safe. Always call this from
* within a synchronized block.
*
* @param raw a string of arbitrary length
* @return void
*/
public String parseLine(final String raw) {
final String delimiter = ":";
if(cid == null || cid.length() &lt; 1) {
throw new RuntimeException(&quot;CID cannot be null.&quot;);
}
if(raw.length() &lt; 5) {
throw new RuntimeException(&quot;Malformed line in log, too short line [&quot;+line_cntr+&quot;]&quot;);
}
int first_delim = raw.indexOf(delimiter);
if(first_delim &lt; 0) {
throw new RuntimeException(&quot;Malformed line in log, has no delimiters line [&quot;+line_cntr+&quot;]&quot;);
}
String residual = raw.substring(first_delim + 1);
if(residual.indexOf(delimiter)&lt; 0) {
throw new RuntimeException(&quot;Malformed line in log, has only one delimiter line [&quot;+line_cntr+&quot;]&quot;);
}
String[] fields = raw.split(delimiter);
if(cid.equals(fields[0])) {
return(raw);
} else {
return(null);
}
}</code></pre></figure>
The Write Requirement
As is mentioned in Implementation Details, the Writer has a race condition that it must handle. It does this with a single Java semaphore.
The code implementing the write function is:
/**
* Writes a message to the commit log.
*
* If it is successful, it returns silently.
*
* If it fails, it throws a RuntimeException, with the error
* set to the explanation of the failure.
*
* @param msg a string of arbitrary length
* @return void
*/
public final void commit(final String msg) {
if(msg.length() < 1) {
throw new RuntimeException("Cannot commit null string.");
}
if(cid.length() < 1) {
throw new RuntimeException("Must set CID before logging entries.");
}
try {
//TODO Create test to simulate multiple writes
synchronized(this) {
// Formatting does not require semaphore
String s = formatLine(msg) + "\r\n";
// Be sure our writes are atomic
available.acquire();
// Open our file writer
fileWriter = new FileWriter(fh, true);
fileWriter.append(s);
fileWriter.flush();
available.release();
}
} catch(IOException | InterruptedException e) {
throw new RuntimeException("IO Error writing to log file ["+fh.getPath()+"] "+e);
}
}
Of note here is the use of synchronized to prevent multiple threads from stamping on each other's shared resources (inside library calls).
Of additional note is the use of semaphores. The line
available.acquire();
Obtains the semaphore. And the line
available.release();
Releases the semaphore. The maximum number of semaphore holders in this case is 1. This is shown in this line of code:
// Semaphore for concurrency control
private final Semaphore available = new Semaphore(1, true);
The loop above employs a utility method called formatLine, which is implemented thus:
/**
* Formats a single line for writing into a log file.
*
* Note, this is NOT thread safe, so always call it from
* within a synchronized block if multi-threading.
*
* @param msg a string of arbitrary length
* @return string for writing to log file
*/
public String formatLine(final String msg) {
final String delimiter = ":";
if(cid.length() &lt; 1) {
throw new RuntimeException(&quot;CID cannot be null.&quot;);
}
String stamp = Objects.toString(System.currentTimeMillis(), null);
SecureRandom random = new SecureRandom();
String rand = new BigInteger(130, random).toString(32).substring(0, 4);
String ret = this.cid + delimiter + stamp + &quot;-&quot; + rand + delimiter + msg;
return ret;
}</code></pre></figure>
The only bit of oddment here is my use of SecureRandom to create the psuedo-random suffix for the Unique ID on the message. This is probably overkill, but using only Java's psuedo-random method on its own has the potential to yield identical results depending on the seeding. To reduce the risk of this further, I use SecureRandom, which, in turn, uses the current system time in milliseconds.