Thread Java 30 days- day 4(Synchronized detail)

paul chou
1 min readAug 2, 2023

--

1. Synchronized Method


synchronized public void syncMethod() {
// …
}

This type of synchronized usage locks the object associated with the method’s instance. If more than one instance of the object is created using “new,” it might not protect the method’s code properly.

However, if the object is only instantiated once, for example, created and stored in ServletContext, and then accessed whenever needed, this issue can be avoided.

2. Synchronized Static Method


synchronized static public void syncMethod() {
// …
}

This type of synchronized usage locks the Class associated with the method. Regardless of how many instances of the Class are created, it ensures that only one thread executes the method at a time.

3. Synchronized(this)


public void syncMethod() {
synchronized(this) {
// …
}
}

This type of synchronized usage, similar to synchronized methods, locks the object itself that the method belongs to.

4. Synchronized(SomeObject)


public void syncMethod() {
synchronized(SomeObject) {
// …
}
}

This type of synchronized usage locks the specific “SomeObject.” If “SomeObject” is two different instances, multiple threads may execute the synchronized block simultaneously.

If every synchronized block uses the same instance of “SomeObject” (or if “SomeObject” itself is static), it ensures that only one thread executes the block at any given time.

When using “synchronized (SomeObject),” “SomeObject” is in a locked state. However, the values inside “SomeObject” can still be modified. The lock only synchronizes the access to the object itself and does not prevent data modification.

--

--