Пример #1
0
  /** Commit and save all changes, if there are any, and compact the storage if needed. */
  public void writeInBackground(int autoCommitDelay) {
    if (closed) {
      return;
    }

    // could also commit when there are many unsaved pages,
    // but according to a test it doesn't really help
    long time = getTimeSinceCreation();
    if (time <= lastCommitTime + autoCommitDelay) {
      return;
    }
    if (hasUnsavedChanges()) {
      try {
        commitAndSave();
      } catch (Exception e) {
        if (backgroundExceptionHandler != null) {
          backgroundExceptionHandler.uncaughtException(null, e);
          return;
        }
      }
    }
    if (autoCompactFillRate > 0 && lastChunk != null && lastChunk.fileStorage != null) {
      FileStorage fileStorage = lastChunk.fileStorage;
      try {
        // whether there were file read or write operations since
        // the last time
        boolean fileOps;
        long fileOpCount = fileStorage.getWriteCount() + fileStorage.getReadCount();
        if (autoCompactLastFileOpCount != fileOpCount) {
          fileOps = true;
        } else {
          fileOps = false;
        }
        // use a lower fill rate if there were any file operations
        int fillRate = fileOps ? autoCompactFillRate / 3 : autoCompactFillRate;
        // TODO how to avoid endless compaction if there is a bug
        // in the bookkeeping?
        compact(fillRate, autoCommitMemory);
        autoCompactLastFileOpCount = fileStorage.getWriteCount() + fileStorage.getReadCount();
      } catch (Exception e) {
        if (backgroundExceptionHandler != null) {
          backgroundExceptionHandler.uncaughtException(null, e);
        }
      }
    }
  }