Permalink
Browse files

one tmp file per test, reasons for volatile and daemon thread

  • Loading branch information...
1 parent b28fe09 commit 794abc271d82fa48681657b41e35eabb420e5172 @Tibor17 committed Nov 16, 2012
@@ -31,7 +31,7 @@ public void evaluate() throws Throwable {
private StatementThread evaluateStatement() throws InterruptedException {
StatementThread thread = new StatementThread(fOriginalStatement);
- thread.setDaemon(true);
+ thread.setDaemon(true);//Let the process/application complete even if this thread is not finished.
thread.start();
fTimeUnit.timedJoin(thread, fTimeout);
if (!thread.fFinished) {
@@ -59,6 +59,19 @@ private void throwTimeoutException(StatementThread thread) throws Exception {
private static class StatementThread extends Thread {
private final Statement fStatement;
+
+ /**
+ * Without modifier of volatile, the values in these variables
+ * may become old in {@link FailOnTimeout#evaluate()}.
+ * When declaring 'volatile' variables, the CPU is forced
+ * to reconcile the values stored in registers and thread's stack
+ * by cache coherence at every write-read operation on these variables
+ * ; Otherwise the CPU and VM may reconcile the memories as it wants
+ * (for performance reasons) and therefore these values read in
+ * {@link FailOnTimeout#evaluate()} may not be up-to-date without volatile.
+ * Besides visibility, the volatile variables have also other guarantees:
+ * atomicity and ordering.
+ * */
private volatile boolean fFinished;
private volatile Throwable fExceptionThrownByOriginalStatement;
private volatile StackTraceElement[] fRecordedStackTrace;
@@ -62,13 +62,15 @@ public void run5() throws IOException {
logger.append("run5");
Random rnd = new Random();
byte[] data = new byte[1024];
+ File tmp = File.createTempFile("dummy", ".tmp");
+ tmp.deleteOnExit();
while (true) {
- File tmp = File.createTempFile("dummy", ".tmp");
- tmp.deleteOnExit();
- FileChannel in = new RandomAccessFile(tmp, "rw").getChannel();
+ FileChannel channel = new RandomAccessFile(tmp, "rw").getChannel();
rnd.nextBytes(data);
- in.write(ByteBuffer.wrap(data));//Interrupted thread closes channel and throws ClosedByInterruptException.
- in.close();
+ ByteBuffer buffer = ByteBuffer.wrap(data);
+ channel.write(buffer);//Interrupted thread closes channel and throws ClosedByInterruptException.
+ channel.close();
+ tmp.delete();
}
}

0 comments on commit 794abc2

Please sign in to comment.