Recently doing a project, there has been a very strange problem, debug mode, step by step, found that asynchronous sending an MQ message is no problem, but in the test environment there will be a problem
The code is as follows:
list<b> dataList = new arraylist<> (); for (b B:a.getb ()) {//processing logic message = Butils.createmessage (b, false);// Datalist.add (message);// Datalisttemp.addall (DataList), Synccrtexecutor.submit (New Bcallable (DataList, QName, Amqsender));d atalist.clear () ;//Empty message contents}
public class Bcallabe implements callable<boolean> {
private static final Logger Logger = Loggerfactory.getlogger (Bcallabe. Class);
Private list<b> dataList = new arraylist<> ();
Private String QName;
Private Amqqueuesender Amqqueuesender;
Public bcallable (list<b> dataList, String QName;,
Amqqueuesender Amqqueuesender) {
This.datalist=datalist;
This.qname = QName;
This.amqqueuesender =amqqueuesender;
}
@Override
Public Boolean Call () throws Exception {
try {
Logger.info ("MQ message pushed to xxx{}", Jsonutil.tostring (dataList));
Amqqueuesender.send (Jsonutil.tostring (dataList),
QName);
} catch (Exception e) {
Logger.error ("MQ message send failed {}", E);
}
return true;
}
}
Because I want to send a message, so every time I get the DataList to forward, but I think the message is more, need to empty, so add datalist.clear ();//Empty the message content, resulting in bcallable message in a shallow copy, or use this value, Causes each send message to be empty
It was thought that this value thread is asynchronous, in the test environment will go straight to clear, resulting in DataList value is emptied, bcallable not get the value of this datailst
Just beginning to think is to write a copy in the outer layer, and then copy in put callable, later give up, now think of the solution:
Public bcallable (list<b> dataList, String qname;,amqqueuesender amqqueuesender) {this.dataList.addAll ( dataList); this.qname = Qname;this.amqqueuesender =amqqueuesender;}
When constructing the callable, the values are copied directly, not duplicated, because the assignment is a shallow copy
Multi-threaded Access collection deep copy and shallow copy