Skip to content

Commit ebec0cb

Browse files
committed
Ensure session counts are reported thread safe
1 parent 1ef85e5 commit ebec0cb

2 files changed

Lines changed: 43 additions & 4 deletions

File tree

bugsnag/src/main/java/com/bugsnag/Bugsnag.java

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -472,11 +472,16 @@ public boolean notify(Report report, Callback reportCallback) {
472472
Session session = sessionTracker.getSession();
473473

474474
if (session != null) {
475-
if (report.getUnhandled()) {
476-
session.incrementUnhandledCount();
477-
} else {
478-
session.incrementHandledCount();
475+
try {
476+
if (report.getUnhandled()) {
477+
session = session.incrementUnhandledCountAndClone();
478+
} else {
479+
session = session.incrementHandledCountAndClone();
480+
}
481+
} catch (InterruptedException ex) {
482+
// Failed to increment session counts properly
479483
}
484+
480485
report.setSession(session);
481486
}
482487

bugsnag/src/main/java/com/bugsnag/Session.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
import com.bugsnag.serialization.Expose;
44

55
import java.util.Date;
6+
import java.util.concurrent.Semaphore;
67
import java.util.concurrent.atomic.AtomicInteger;
78

89
class Session {
910

11+
private final Semaphore incrementRequest = new Semaphore(1);
12+
1013
private final String id;
1114
private final Date startedAt;
1215
private final AtomicInteger handledCount;
@@ -19,6 +22,13 @@ class Session {
1922
this.unhandledCount = new AtomicInteger(0);
2023
}
2124

25+
private Session(String id, Date startedAt, int handledCount, int unhandledCount) {
26+
this.id = id;
27+
this.startedAt = startedAt;
28+
this.handledCount = new AtomicInteger(handledCount);
29+
this.unhandledCount = new AtomicInteger(unhandledCount);
30+
}
31+
2232
int getHandledCount() {
2333
return handledCount.get();
2434
}
@@ -27,6 +37,16 @@ void incrementHandledCount() {
2737
this.handledCount.incrementAndGet();
2838
}
2939

40+
Session incrementHandledCountAndClone() throws InterruptedException {
41+
try {
42+
incrementRequest.acquire();
43+
incrementHandledCount();
44+
return cloneSession();
45+
} finally {
46+
incrementRequest.release();
47+
}
48+
}
49+
3050
int getUnhandledCount() {
3151
return unhandledCount.get();
3252
}
@@ -35,6 +55,20 @@ void incrementUnhandledCount() {
3555
this.unhandledCount.incrementAndGet();
3656
}
3757

58+
Session incrementUnhandledCountAndClone() throws InterruptedException {
59+
try {
60+
incrementRequest.acquire();
61+
incrementUnhandledCount();
62+
return cloneSession();
63+
} finally {
64+
incrementRequest.release();
65+
}
66+
}
67+
68+
private Session cloneSession() {
69+
return new Session(id, startedAt, handledCount.get(), unhandledCount.get());
70+
}
71+
3872
String getId() {
3973
return id;
4074
}

0 commit comments

Comments
 (0)