15
Q 4. How does synchronization work in Java? Explain the
concepts of synchronized methods and blocks.
Using synchronized methods
Using synchronized blocks
Synchronization in Java is a mechanism that allows multiple
threads to access shared resources safely. When a thread is
synchronized on a resource, it is the only thread that can access
that resource.
This prevents race conditions, which are situations where two or
more threads are trying to access the same resource at the same
time.
There are two ways to synchronize in Java:
Synchronized methods
A synchronized method is a method that can only be executed by
one thread at a time. To declare a method as synchronized, you
need to use the synchronized keyword.
Synchronized blocks
A synchronized block is a block of code that can only be executed
by one thread at a time. To declare a block of code as
synchronized, you need to use the synchronized keyword and
specify the object that the block is synchronized on.
Ans:
Q 5. What is a deadlock, and how can it be avoided?
Avoid using locks unnecessarily.
Use locks in a consistent order.
Use deadlock detection and prevention tools.
A deadlock is a situation where two or more threads are waiting
for each other to finish. This can happen when two threads are
each trying to acquire a lock on the same resource.
To avoid deadlocks, we can do this:
Ans: