In Java, you can use the synchronized
keyword to synchronize access to an object and ensure that only one thread can execute a particular block of code at a time. This is known as obtaining a lock on the object.
Here is an example of how to use the synchronized
keyword to obtain a lock on an object:
class MyClass { private final Object lock = new Object(); public void doSomething() { synchronized (lock) { // code that needs to be synchronized goes here } } }
In this example, the lock
field is an object that is used as a lock. The doSomething
method synchronizes on the lock
object using the synchronized
keyword. This ensures that only one thread can execute the code inside the synchronized
block at a time.
You can also use the synchronized
keyword to synchronize on the this
object, which represents the current instance of the class.
For example:
class MyClass { public void doSomething() { synchronized (this) { // code that needs to be synchronized goes here } } }
In this example, the doSomething
method synchronizes on the this
object, which ensures that only one thread can execute the code inside the synchronized
block at a time.
It is important to note that the synchronized
keyword can have a negative impact on performance, as it can cause contention and lock contention among threads. Therefore, it is generally recommended to use the synchronized
keyword only when it is necessary to ensure thread safety, and to minimize the amount of code that is synchronized.