Skip to content

Commit

Permalink
fix race condition in BackendSessionPool.close()
Browse files Browse the repository at this point in the history
The following code: "if (this.sessionCount.get() == 0)"
may cause multiple threads to call doClose() at the same time

Change-Id: Ib4eb69533a2da7e4b05a52df75c31557bb592636
  • Loading branch information
javeme authored and zhoney committed Jan 14, 2019
1 parent 0e63594 commit efe3676
Showing 1 changed file with 20 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;

import com.baidu.hugegraph.config.HugeConfig;
Expand Down Expand Up @@ -63,39 +64,42 @@ public BackendSession useSession() {
return session;
}

public int closeSession() {
public Pair<Integer, Integer> closeSession() {
BackendSession session = this.threadLocalSession.get();
if (session == null) {
LOG.warn("Current session has ever been closed");
return -1;
return Pair.of(this.sessionCount.get(), -1);
}

int ref = session.detach();
assert ref >= 0 : ref;
if (ref == 0) {
try {
session.close();
} catch (Throwable e) {
session.attach();
throw e;
}
this.threadLocalSession.remove();
this.sessionCount.decrementAndGet();
if (ref > 0) {
return Pair.of(this.sessionCount.get(), ref);
}

// Close session when ref=0
try {
session.close();
} catch (Throwable e) {
session.attach();
throw e;
}
return ref;
this.threadLocalSession.remove();
return Pair.of(this.sessionCount.decrementAndGet(), ref);
}

public void close() {
int ref = -1;
Pair<Integer, Integer> result = Pair.of(-1, -1);
try {
ref = this.closeSession();
result = this.closeSession();
} finally {
if (this.sessionCount.get() == 0) {
if (result.getLeft() == 0) {
this.doClose();
}
}
LOG.debug("Now(after close({})) session count is: {}, " +
"current session reference is: {}",
this, this.sessionCount.get(), ref);
this, result.getLeft(), result.getRight());
}

public boolean closed() {
Expand Down

0 comments on commit efe3676

Please sign in to comment.