java - Should I synchronize method in my example? -
i'm not sure if should synchronize method methodone() in example. think not i'm not 100% sure. please give me advice do?
public class synchroissue { class test { private double = 0; void methodone() { a++; } void go() { new thread(new runnable() { @override public void run() { (int = 0; < integer.max_value; i++) { methodone(); system.out.println(thread.currentthread().getname() + ", = " + a); } } }).start(); } } public static void main(string... args) { synchroissue mainobj = new synchroissue(); synchroissue.test object1 = mainobj.new test(); synchroissue.test object2 = mainobj.new test(); object1.go(); object2.go(); } }
assuming going use instances of synchroissue class concurrently, not doing currently, answer yes.
the increment operator not atomic. 3 instructions:
get current value.
add 1 that.
store new value.
if not synchronized, concurrent threads can overlap steps resulting in strange behavior.
another option, if interested in integers, use of atomicinteger, has methods atomically increment.
Comments
Post a Comment