Added support for registering listeners with the database that are

called when new messages are available, and a new method
hasSendableMessages(ContactId) that listeners can call to see whether
it's worth trying to create a batch.
This commit is contained in:
akwizgran
2011-07-27 20:27:43 +01:00
parent e93fbe0b20
commit adee3e121c
10 changed files with 364 additions and 99 deletions

View File

@@ -1,5 +1,8 @@
package net.sf.briar.db;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -7,6 +10,7 @@ import net.sf.briar.api.ContactId;
import net.sf.briar.api.Rating;
import net.sf.briar.api.db.DatabaseComponent;
import net.sf.briar.api.db.DbException;
import net.sf.briar.api.db.MessageListener;
import net.sf.briar.api.db.Status;
import net.sf.briar.api.protocol.AuthorId;
import net.sf.briar.api.protocol.Message;
@@ -25,6 +29,8 @@ DatabaseCleaner.Callback {
protected final Database<Txn> db;
protected final DatabaseCleaner cleaner;
private final List<MessageListener> listeners =
new ArrayList<MessageListener>(); // Locking: self
private final Object spaceLock = new Object();
private final Object writeLock = new Object();
private long bytesStoredSinceLastCheck = 0L; // Locking: spaceLock
@@ -41,6 +47,18 @@ DatabaseCleaner.Callback {
cleaner.startCleaning();
}
public void addListener(MessageListener m) {
synchronized(listeners) {
listeners.add(m);
}
}
public void removeListener(MessageListener m) {
synchronized(listeners) {
listeners.remove(m);
}
}
/**
* Removes the oldest messages from the database, with a total size less
* than or equal to the given size.
@@ -61,6 +79,18 @@ DatabaseCleaner.Callback {
return sendability;
}
/** Notifies all MessageListeners that new messages may be available. */
protected void callMessageListeners() {
synchronized(listeners) {
if(!listeners.isEmpty()) {
// Shuffle the listeners so we don't always send new messages
// to contacts in the same order
Collections.shuffle(listeners);
for(MessageListener m : listeners) m.messagesAdded();
}
}
}
public void checkFreeSpaceAndClean() throws DbException {
long freeSpace = db.getFreeSpace();
while(freeSpace < MIN_FREE_SPACE) {
@@ -85,7 +115,7 @@ DatabaseCleaner.Callback {
}
/**
* Returns true iff the database contains the given contact.
* Returns true if the database contains the given contact.
* <p>
* Locking: contacts read.
*/
@@ -121,7 +151,7 @@ DatabaseCleaner.Callback {
if(bytesStoredSinceLastCheck > MAX_BYTES_BETWEEN_SPACE_CHECKS) {
if(LOG.isLoggable(Level.FINE))
LOG.fine(bytesStoredSinceLastCheck
+ " bytes stored since last check");
+ " bytes stored since last check");
bytesStoredSinceLastCheck = 0L;
timeOfLastCheck = now;
return true;
@@ -234,7 +264,7 @@ DatabaseCleaner.Callback {
}
if(LOG.isLoggable(Level.FINE))
LOG.fine(direct + " messages affected directly, "
+ indirect + " indirectly");
+ indirect + " indirectly");
}
/**