user1300214
user1300214

Reputation:

Thread deadlocking and synchronization

I know that I need to use synchronization appropriately in order to avoid deadlocking when using multiple threads, but I was wondering:

Do I need to synchronize for both amending the value of and examining a variable, or do I just need to synchronize when I amend the value, but not when I examine the variable?

Upvotes: 0

Views: 81

Answers (5)

Sambusak
Sambusak

Reputation: 43

If you have a resource that is not thread-safe, you'll need to protect both examining and amending its value.

Upvotes: 0

java seeker
java seeker

Reputation: 1266

Synchronized do not use to avoid deadlock

Synchronize keyword ensure thread safely in multithreading environment. Though you have a multi thread, you want to amending and examining member variables.

To do it create a class which contains data variables that you want to thread safed. create synchronized function for appending and examining variables.

class exam
{
 ....

 synchronized void examine()
 {}


 synchronized void amending()
 {}


}

create a single object of the class and pass it to your all thread.

Upvotes: 0

vipul mittal
vipul mittal

Reputation: 17401

as Darkhogg mentioned synchronization causes deadlocks if not used properly.

You need to synchronize code blocks on a data members that are updating(changing data members) the value and can be executed by multiple thread.

Make it synchronized will insure that the data members will not be updated simultaneously.

Upvotes: 1

Ralf
Ralf

Reputation: 6853

As for the deadlocking: Darkhogg already correctly pointed out that deadlocking is a result from incorrect synchronization and workflow.

Synchronizing state modifications and state observation: Yes, you need to synchronize both. The effect of the object lock you obtain when entering a synchronized method is that no other thread my enter the same or another synchronized code block that requires the same object lock (synhronizes on the same object). That said, if you do not synchronize the code that observes the state of your object, then this code might be executed concurrently to the synchronized code that modifies the state and you may read an invalid object state.

Upvotes: 1

RMachnik
RMachnik

Reputation: 3684

Read that article this my get you better knowledge base about synchronization http://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html

Upvotes: 0

Related Questions