multithreading - Using Java, is this type of setup and call from a method thread safe? -
i have service class implementation of interface , it's annotated spring service , singleton. have 2 different methods each creates string builder local variable. have private method takes string builder , string, , both parameters final variables. private method appends information string builder depending on information found in additional string variable. in each implemented method call private method passing locally created string builder , necessary string.
i confident 2 implemented methods thread safe, unsure private method. string builder thread safe when pass that? having parameters final help? assumed final made thread safe, @ same time thought having final means couldn't append it.
this stackoverflow question , answer says wouldn't be, in example parameter not final, maybe not matter.
is stringbuilder variable thread safe in code?
here's example of have:
@service @scope("singleton") public class singletonservice { @override public string buildselect(final integer id){ stringbuilder sb = new stringbuilder("select * 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) 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); } } }
final has absolutely no effect when used in method signature other making can't accidentally assign variable inside method.
other ... why wouldn't code thread safe?
the thing you're passing in public methods integer immutable , nothing else external methods ever modified.
so yes, since there's no concurrency involved, threadsafe.
that said, doesn't make lot of sense. you're creating map, putting in it, discarding it.
Comments
Post a Comment