The synchronized keyword is used in two related ways in Java: as a modifier and as a statement First, it is a modifier applied to class or instance methods It indicates that the method modifies the internal state of the class or the internal state of an instance of the class in a way that is not thread-safe Before running a synchronized class method, Java obtains a lock on the class, to ensure that no other threads can modify the class concurrently Before running a synchronized instance method, Java obtains a lock on the instance that invoked the method, ensuring that no other threads can modify the object at the same time Java also supports a synchronized statement that serves to specify a "critical section" of code The synchronized keyword is followed by an expression in parentheses, and a statement or block of statements The expression must evaluate to an object or array Java obtains a lock on the specified object or array before executing the statements
A keyword in the Java programming language that, when applied to a method or code block, guarantees that at most one thread at a time executes that code Unless synchronized is specified separate threads can exist in a method simultaneously Methods that access shared data should be synchronized to give them mutually exclusive access