Tidied up synchronization.

This commit is contained in:
akwizgran
2011-10-13 13:08:54 +01:00
parent aabe72bfd7
commit d54ca67fe9
2 changed files with 31 additions and 29 deletions

View File

@@ -11,7 +11,7 @@ interface DatabaseCleaner {
*/ */
void startCleaning(Callback callback, long msBetweenSweeps); void startCleaning(Callback callback, long msBetweenSweeps);
/** Tells the cleaner thread to exit and returns when it has done so. */ /** Tells the cleaner thread to exit. */
void stopCleaning(); void stopCleaning();
interface Callback { interface Callback {

View File

@@ -1,49 +1,51 @@
package net.sf.briar.db; package net.sf.briar.db;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.briar.api.db.DbException;
class DatabaseCleanerImpl implements DatabaseCleaner, Runnable { class DatabaseCleanerImpl implements DatabaseCleaner, Runnable {
private final Object lock = new Object(); private static final Logger LOG =
private final Thread cleanerThread = new Thread(this); Logger.getLogger(DatabaseCleanerImpl.class.getName());
private volatile Callback callback; private Callback callback = null;
private volatile long msBetweenSweeps; private long msBetweenSweeps = 0L;
private volatile boolean stopped = false; // Locking: lock private boolean stopped = false;
public void startCleaning(Callback callback, long msBetweenSweeps) { public synchronized void startCleaning(Callback callback,
long msBetweenSweeps) {
this.callback = callback; this.callback = callback;
this.msBetweenSweeps = msBetweenSweeps; this.msBetweenSweeps = msBetweenSweeps;
cleanerThread.start(); new Thread(this).start();
} }
public void stopCleaning() { public synchronized void stopCleaning() {
// If the cleaner thread is waiting, wake it up stopped = true;
synchronized(lock) { notifyAll();
stopped = true;
lock.notifyAll();
}
try {
cleanerThread.join();
} catch(InterruptedException ignored) {}
} }
public void run() { public void run() {
try { while(true) {
while(true) { synchronized(this) {
if(callback.shouldCheckFreeSpace()) { if(stopped) return;
callback.checkFreeSpaceAndClean(); try {
} else { if(callback.shouldCheckFreeSpace()) {
synchronized(lock) { callback.checkFreeSpaceAndClean();
if(stopped) break; } else {
try { try {
lock.wait(msBetweenSweeps); wait(msBetweenSweeps);
} catch(InterruptedException ignored) {} } catch(InterruptedException ignored) {}
} }
} catch(DbException e) {
if(LOG.isLoggable(Level.WARNING))
LOG.warning(e.getMessage());
} catch(RuntimeException e) {
if(LOG.isLoggable(Level.WARNING))
LOG.warning(e.getMessage());
} }
} }
} catch(Throwable t) {
// FIXME: Work out what to do here
t.printStackTrace();
System.exit(1);
} }
} }
} }