在我的项目中,我们使用带有 spring 框架的 Restful Webservices,当我同时调用相同的请求时, 对象被另一个对象覆盖。
下面是我的代码。
@Service("testService")
@Scope(value ="prototype")
public class TestServiceImpl extends DefaultServiceBuilder {
public void test() {
process();
System.err.println(tranLog.getTxnId());
}
}
public class DefaultServiceBuilder {
protected TransactionLog tranLog;
public void process() {
tranLog = new TransactionLog();
Random r = new Random();
String rid = r.nextInt(40000)+"";
tranLog.setTxnid(rid);
setTranLog(tranLog);
}
public TransactionLog getTranLog() {
return tranLog;
}
public void setTranLog(TransactionLog tranLog) {
this.tranLog = tranLog;
}
}
public class TransactionLog {
private String txnId;
public void setTxnId(String txnId) {
this.txnId = txnId;
}
public String getTxnId() {
return txnId;
}
}
我正在使用 2 个线程并行调用以下请求。
My expected input is
123456
242422
But the output is
242422
242422
为什么即使我给出了作用域原型(prototype),TransactionLog 对象值仍然会被覆盖。 如何安全地访问Transalog对象?
任何帮助将不胜感激!!!!
最佳答案
您可以通过同步以下代码行来同步您的代码
protected static TransactionLog tranLog;
public static synchronized void process() {
Random r = new Random();
tranLog = new TransactionLog();
String rid = r.nextInt(40000)+"";
tranLog.setTxnid(rid);
}
设置静态同步
将在任何给定时间只允许一个线程。
关于java - 并发请求中rest api数据不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48519407/