The question is fairly self-explanatory, but to add a little background, here's the scenario that has made me ask. First a (very basic) SSCCE:
public void createAttachments(List<Account> accounts) {
Map<Attachment, Account> attachmentAccountMap = getMap(accounts);
for (Attachment attachment : attachmentAccountMap.keySet()) {
System.debug(attachment.Name);
Account account = attachmentAccountMap.get(attachment);
System.assertNotEquals(null, account);
}
}
private Map<Attachment, Account> getMap(List<Account> accounts) {
Map<Attachment, Account> attachmentAccountMap = new Map<Attachment, Account>();
List<Attachment> attachments = new List<Attachment>();
for (Account account : accounts) {
Attachment attachment = new Attachment();
attachment.Name = 'test';
attachments.add(attachment);
attachmentAccountMap.put(attachment, account);
}
insert attachments;
return attachmentAccountMap;
}
The problem I had seemed to be a race condition at the System.assertNotEquals()
line - on most occasions the assertion passed, and the account was not null, but sometimes it would fail. Increasing the logging seemed to cause it to fail consistently, and reducing it seemed to make it pass consistently, which is why I think it was a race condition.
There are 2 relatively simple triggers on Attachment (before and after insert), which (I don't think) should affect my attachments, but I'm not certain.
What seems to be happening is that somewhere between the start of the for loop in createAttachments()
, where attachment
is assigned as the first key in the map, and the assertion, the attachment in the map is changed (maybe because the ID gets set?), so when we try to use it to retrieve an account from the map, the two objects are no longer equal, and the get
returns null.
Does anyone know if this sounds right???
I seem to have managed to resolve it for my case by just swapping the objects in the map, so making it Map<Account, Attachment>
, because I'm really just using the map to keep the two objects associated - the better solution would probably have been to make a new class with the two objects, but I didn't do that!