Skip to content

Commit 190767e

Browse files
committed
Improve nodeId generation to prevent conflicts in distributed environments
Signed-off-by: Hyun Jong Park <[email protected]>
1 parent 75b216c commit 190767e

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/mongodb/MongoSequenceIncrementer.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
import org.springframework.dao.DataAccessException;
1919
import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
2020

21+
import java.net.InetAddress;
22+
import java.security.SecureRandom;
2123
import java.util.concurrent.atomic.AtomicInteger;
2224

2325
/**
@@ -40,8 +42,10 @@ public class MongoSequenceIncrementer implements DataFieldMaxValueIncrementer {
4042
private final AtomicInteger sequence = new AtomicInteger(0);
4143
private volatile long lastTimestamp = -1L;
4244

45+
private static final SecureRandom random = new SecureRandom();
46+
4347
public MongoSequenceIncrementer() {
44-
this.nodeId = (int) (System.nanoTime() & NODE_MASK);
48+
this.nodeId = calculateNodeId();
4549
}
4650

4751
public MongoSequenceIncrementer(int nodeId) {
@@ -95,4 +99,16 @@ private long waitNextMillis(long lastTimestamp) {
9599
return timestamp;
96100
}
97101

102+
private int calculateNodeId() {
103+
try {
104+
String hostname = InetAddress.getLocalHost().getHostName();
105+
int hostHash = hostname.hashCode();
106+
long processId = ProcessHandle.current().pid();
107+
long randomValue = random.nextInt();
108+
return (int) ((hostHash ^ processId ^ randomValue) & NODE_MASK);
109+
} catch (Exception e) {
110+
return (int) ((System.nanoTime() ^ Thread.currentThread().getId()) & NODE_MASK);
111+
}
112+
}
113+
98114
}

0 commit comments

Comments
 (0)