I have a method:
private List<String> userCns = Collections.synchronizedList(new ArrayList<String>());
private List<String> recipients = Collections.synchronizedList(new ArrayList<String>());
public void sendEmailToLegalUsers() {
try {
synchronized (lock) {
searchGroup();
if(userCns.size() > 0) {
for(String userCn : userCns) {
String mail = getUserMail(userCn);
if(mail != null) {
recipients.add(mail);
}
}
}
String docName = m_binder.getLocal("docname");
String docId = m_binder.getLocal("docid");
String url = m_binder.getLocal("serverURL");
if(recipients.size() > 0) {
m_binder.addResultSet("LOI_EVIN_MAIL", getLoiEvinMailResultSet(docName, docId, url));
for(String recipient : recipients) {
Log.info("Sending mail to: " + recipient);
InternetFunctions.sendMailToEx(recipient, "MH_LOI_EVIN_SEND_EMAIL", "Update Evin Law Compliance for the item: " + docName, m_service, true);
}
}
}
} catch (Exception e) {
Log.info("Error occurred in LDAPSendMail: "+ e.getMessage());
}
}
Now this sendEmailToLegalUsers method can be called from different threads. I am wondering is it the right way to lock the code block so that there is no chances of data mixup in the list?
Edit: whole class:
package com.edifixio.ldapsendmail.handlers;
import intradoc.common.Log;
import intradoc.data.DataResultSet;
import intradoc.server.InternetFunctions;
import intradoc.server.ServiceHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
public class LDAPSendMail extends ServiceHandler {
private final Object lock = new Object();
private String ldapURL;
private String baseDN;
private String groupDN;
private String username;
private String password;
private DirContext context;
private List<String> userCns = Collections.synchronizedList(new ArrayList<String>());
private List<String> recipients = Collections.synchronizedList(new ArrayList<String>());
public void sendEmailToLegalUsers() {
try {
synchronized (lock) {
searchGroup();
if(userCns.size() > 0) {
for(String userCn : userCns) {
String mail = getUserMail(userCn);
if(mail != null) {
recipients.add(mail);
}
}
}
String docName = m_binder.getLocal("docname");
String docId = m_binder.getLocal("docid");
String url = m_binder.getLocal("serverURL");
if(recipients.size() > 0) {
m_binder.addResultSet("LOI_EVIN_MAIL", getLoiEvinMailResultSet(docName, docId, url));
for(String recipient : recipients) {
Log.info("Sending mail to: " + recipient);
InternetFunctions.sendMailToEx(recipient, "MH_LOI_EVIN_SEND_EMAIL", "Update Evin Law Compliance for the item: " + docName, m_service, true);
}
}
userCns.clear();
recipients.clear();
}
} catch (Exception e) {
Log.info("Error occurred in LDAPSendMail: "+ e.getMessage());
}
}
private String getUserMail(String userCn) throws NamingException {
NamingEnumeration<SearchResult> searchResults = getLdapDirContext().search(userCn, "(objectclass=person)", getSearchControls());
while (searchResults.hasMore()){
SearchResult searchResult = searchResults.next();
Attributes attributes = searchResult.getAttributes();
Attribute mail = null;
try {
mail = attributes.get("mail");
} catch (Exception e) {
mail = null;
}
if(mail != null) {
return (String)mail.get();
}
}
return null;
}
private void searchGroup() throws NamingException {
NamingEnumeration<SearchResult> searchResults = getLdapDirContext().search(groupDN, "(objectclass=groupOfUniqueNames)", getSearchControls());
String searchGroupCn = getCNForBrand(m_binder.getLocal("brandId"), m_binder.getLocal("brandName"));
while (searchResults.hasMore()) {
SearchResult searchResult = searchResults.next();
Attributes attributes = searchResult.getAttributes();
Attribute groupCn = null;
try {
groupCn = attributes.get("cn");
} catch (Exception e) {
groupCn = null;
}
if(groupCn != null) {
if(searchGroupCn.equals((String)groupCn.get())) {
Attribute uniqueMembers = attributes.get("uniqueMember");
for(int i = 0; i < uniqueMembers.size(); i++){
String uniqueMemberCN = (String) uniqueMembers.get(i);
userCns.add(uniqueMemberCN);
}
break;
}
}
}
}
private DirContext getLdapDirContext() throws NamingException {
if(context != null) {
return context;
}
ldapURL = m_binder.getLocal("ldapUrl");
baseDN = m_binder.getLocal("baseDN");
groupDN = new StringBuilder().append("ou=").append(getAccountGroup(m_binder.getLocal("account"))).append(",").append("ou=groups,").append(baseDN).toString();
username = m_binder.getLocal("username");
password = m_binder.getLocal("password");
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, ldapURL);
environment.put(Context.SECURITY_PRINCIPAL, username);
environment.put(Context.SECURITY_CREDENTIALS, password);
context = new InitialDirContext(environment);
return context;
}
private SearchControls getSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
return searchControls;
}
private String getCNForBrand(String brandId, String brandName) {
String[] brandIdSplittedArray = brandId.split("/");
return new StringBuilder().append(brandIdSplittedArray[0]).append("-").append(brandIdSplittedArray[1]).append("-").
append(brandIdSplittedArray[2]).append("-").append(brandName.replaceAll("\\s","")).append("-LU").toString();
}
private String getAccountGroup(String account) {
return account.split("/")[1];
}
private DataResultSet getLoiEvinMailResultSet(String docName, String docId, String url) {
DataResultSet resultSet = new DataResultSet(new String[]{"DOCNAME", "DOCID", "URL"});
Vector<String> vector = new Vector<String>();
vector.add(docName);
vector.add(docId);
vector.add(url);
resultSet.addRow(vector);
return resultSet;
}
}
What is
lock? Are you using it elsewhere? Typically you want the synchronized blocks to be pretty small. If you’re usinglockeverywhere as a general purpose lock then you might be stopping a thread from doing some useful work in a totally unrelated area (i.e., one where there is no contention for shared resources).Second, does
recipientsreally need to be an instance variable? It seems strange that you would keep adding emails torecipientswithout checking to see if that email already exists in the list. I can’t see any code where you’re clearing ourrecipientseither. So that is a potential issue. If you are going to be buildingrecipientsfrom scratch every time, then just make it a local variable in the method. If you really need access to that data, you can always pull it out ofuserCns.Once you make
recipientsa local variable, then you only need to synchronize by usinguserCnsas a lock:edit: Your code shows that you only use
recipientsonce, and that’s inside thesendEmailToLegalUsersmethod. Another thing, as I pointed out, is that you never clearrecipientsso that’s a bug in your code. Since you don’t userecipientsanywhere, make it a local variable tosendEmailToLEgalUsers. Also, just synchronize overuserCns. You won’t need to synchronize overrecipients; you can create it inside the synchronized block.