I am receiving messages from multiple gmail accounts using the Java mail API. The different accounts are being processed by different threads, and I am using a LinkedBlockingQueue
to store the emails. However I do not want the same email repeatedly being added to the Queue
.
This is the code I have so far:
public synchronized void readMail(){
try {
boolean alreadyAdded = false;
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message [] received = inbox.getMessages();
if(messages.isEmpty()){
for(Message newMessage:received){
System.out.println("Queue empty, adding messages");
messages.put(newMessage);
}
}
else{
for(Message existingMessage:messages){
for(Message newMessage:received){
if (alreadyAdded == true)
break;
else{
if(existingMessage.getSubject().equals(newMessage.getSubject())){
alreadyAdded = true;
System.out.println("boolean changed to true, message "+newMessage.getSubject()+"won't be added");
}
else{
alreadyAdded = false;
System.out.println("Non-duplicate message "+newMessage.getSubject());
messages.put(newMessage);
}
}
}
}
}
}
catch (MessagingException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
The problem I am having is in the else
block after the if
checking if the Queue is empty. I want it to check through the set of messages that has just been read in and compare those to the messages already in the Queue
. If the message is in the Queue
don't add it again. I cannot simply use .contains()
, as each time messages are downloaded, they are given a different memory location, so although the Message
object may in fact be the same (e.g. has the same subject, content, etc) it will not have the same signature (e.g the first time it is downloaded it may be Messagehgshsh676767
but the next time it could be Messageyyetwt8965
).
I have hit a brick wall, can anyone suggest a way to make sure no duplicates are added?