Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How Thread conflicts can be avoided?  RSS feed

 
saikrishna cinux
Ranch Hand
Posts: 689
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
refering to this link
http://www.javacoffeebreak.com/articles/toptenerrors.html

3. Preventing concurrent access to shared variables by threads
When writing multi-threaded applications, many programmers (myself included) often cut corners, and leave their applications and applets vulnerable to thread conflicts. When two or more threads access the same data concurrently, there exists the possibility (and Murphy's law holding, the probability) that two threads will access or modify the same data at the same time. Don't be fooled into thinking that such problems won't occur on single-threaded processors. While accessing some data (performing a read), your thread may be suspended, and another thread scheduled. It writes its data, which is then overwritten when the first thread makes its changes.

Such problems are not just limited to multi-threaded applications or applets. If you write Java APIs, or JavaBeans, then your code may not be thread-safe. Even if you never write a single application that uses threads, people that use your code WILL. For the sanity of others, if not yourself, you should always take precautions to prevent concurrent access to shared data.

How can this problem be solved? The simplest method is to make your variables private (but you do that already, right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.

public class MyCounter
{
private int count = 0; // count starts at zero

public synchronized void setCount(int amount)
{
count = amount;
}

public synchronized int getCount()
{
return count;
}
}


how can you support the statement that by keeping private variable we can avoid thread conflicts in multi threading environment??

 
Edward Harned
Ranch Hand
Posts: 291
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read the tutorial on concurrency from Sun:

http://java.sun.com/docs/books/tutorial/essential/concurrency/
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Private variables won't help in the theory of things. You can get into trouble any time two threads have access to one object. Anything that exceeds local object instance visibility scope poses a risk - parameters you send or receive, singletons, static variables, etc. It's a scary world, no?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!