Skip to content

Change to discardOldestFileIfNeeded sorting #2189

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
* Sanity check the allocation in the installation of `bugsnag-plugin-android-ndk` to avoid a possible crash when allocation fails
[#2191](https://github.com/bugsnag/bugsnag-android/pull/2191)

* Added deterministic sorting for `discardOldestFileIfNeeded` method to avoid potential crashes when files are being written while sorting the queue
[#2181](https://github.com/bugsnag/bugsnag-android/pull/2189)

## 6.13.0 (2025-04-15)

### Enhancements
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,21 @@ internal abstract class FileStore(
if (isStorageDirValid(storageDir)) {
val listFiles = storageDir.listFiles() ?: return
if (listFiles.size < maxStoreCount) return
val sortedListFiles = listFiles.sortedBy { it.lastModified() }

// Store lastModified to ensure it doesn't change during sort
val timestampedFiles = listFiles.mapTo(ArrayList(listFiles.size)) { file ->
FileWithTimestamp(file, file.lastModified())
}

// Sort by cached lastModified timesstamps
timestampedFiles.sort()

// Number of files to discard takes into account that a new file may need to be written
val numberToDiscard = listFiles.size - maxStoreCount + 1
var discardedCount = 0
for (file in sortedListFiles) {

for (fileMeta in timestampedFiles) {
val file = fileMeta.file
if (discardedCount == numberToDiscard) {
return
} else if (!queuedFiles.contains(file)) {
Expand Down Expand Up @@ -188,3 +198,15 @@ internal abstract class FileStore(
}
}
}

/**
* A data holder for associating a {@link File} with its last modified timestamp.
*
* @param file The file to associate with a timestamp.
* @param timestamp The last modified time of the file, cached to ensure consistent ordering.
*/
private data class FileWithTimestamp(val file: File, val timestamp: Long) : Comparable<FileWithTimestamp> {
override fun compareTo(other: FileWithTimestamp): Int {
return timestamp.compareTo(other.timestamp)
}
}
Loading