Let us assume an object as follows:
My Object {
private String field1 = "";
private String field2 = "";
/*getters and setters for field1 and field2 */
boolean isField1inDocument (String document) {
if (document.indexOf(field1) > -1) return true;
else return false;
}
}
Is the method isField1inDcoument thread safe? I am worried that the boolean value returned by one thread may some how collide with the boolean value created by another thread executing the method at the same time. The documents being fed to the method are from individual threads and the documents themselves can’t collide. I know I can synchronize this method. I’m just trying to figure out if this is necessary.
logically the behavior of isField1inDocument() is dependent on only the document (which you say is only owned by the thread), and the value of field1. You do have setters for field 1 so it’s possible to imagine a scenario where field1 is altered by a different thread while your current thread is doing your isField1inDocument() calculation, so that’s not thread safe.
You could fix this by passing in the field1 value, e.g.
or by holding a private instance of the enclosing MyObject from the caller thread