I've got multi threaded application(for example, servlet). Also I've got a common resource(file, ref or something). How can I synchronize its access? This is how I do:
static Object lock = new Object();
volatile int commonRes = 0;
public void doSomething() {
System.out.println("Before statement " + commonRes);
synchronized (lock) {
//some process
commonRes++;
}
//Do something else
System.out.println("After statement " + commonRes);
}
I have two questions:
- Is it good approach?
- Should
lock
bevolatile
?