I have a service class that is an implementation of an interface and it's annotated with Spring as a service and a singleton. I have two different methods where each creates a string builder local variable. I have a private method that takes a string builder and a string, and both parameters are final variables. This private method appends information to that string builder depending on the information found in that additional string variable. In each implemented method I call that private method passing the locally created string builder and the necessary string.
I am confident that the two implemented methods are thread safe, but I am unsure about the private method. Is that string builder thread safe when I pass it like that? Does having the parameters as final help? I assumed the final made that thread safe, but at the same time I thought having it final means I couldn't append anything to it.
This stackoverflow question and answer says it wouldn't be, but in the example the parameter is not final, but maybe that does not matter.
Is that StringBuilder variable thread safe in this code?
Here's an example of what I have:
@Service
@Scope("singleton")
public class SingletonService {
@Override
public String buildSelect(final Integer id){
StringBuilder sb = new StringBuilder("select * from table ");
Map<String,Object> properties = new HashMap<String,Object>();
addWhere(sb,properties,id);
return sb.toString();
}
@Override
public String buildCount(final Integer id){
StringBuilder sb = new StringBuilder("select count(id) from table ");
Map<String,Object> properties = new HashMap<String,Object>();
addWhere(sb,properties,id);
return sb.toString();
}
private void addWhere(final StringBuilder sb, final Map<String,Object> properties, final Integer id){
if(id != null){
sb.append("where id = :id);
properties.put("id",id);
}
}
}