What is the meaning of the keyword Synchronized?
The keyword synchronized is used in multi-threaded applications, to guarantee consistency of the data and to avoid unexpected results.
When it is used in a method declaration, the JVM will guarantee that once a thread A starts to run this method, other threads that want to run other synchronized methods in the same object will be locked until thread A leaves the synchronized method.
E.g.:
public synchronized int getFoo() { return foo++; }
This keyword can also be used in a synchronized statement, to improve the application performance, as when not all of the lines of code in the method need to synchronized. It is necessary to declare which object will be synchronized (use this to synchronize the object that has the method).
E.g.:
public int foo() {
synchronized(this){
foo++;
}
//do something else...
}
The keyword synchronized is used in multi-threaded applications, to guarantee consistency of the data and to avoid unexpected results.
When it is used in a method declaration, the JVM will guarantee that once a thread A starts to run this method, other threads that want to run other synchronized methods in the same object will be locked until thread A leaves the synchronized method.
E.g.:
public synchronized int getFoo() { return foo++; }
This keyword can also be used in a synchronized statement, to improve the application performance, as when not all of the lines of code in the method need to synchronized. It is necessary to declare which object will be synchronized (use this to synchronize the object that has the method).
E.g.:
public int foo() {
synchronized(this){
foo++;
}
//do something else...
}
No comments:
Post a Comment
Please, before starting to comment, evaluate if what you want to write is useful, respectful and positive. A kid may read this also.
Give a good example!