This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes threads and inconsistent class variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "threads and inconsistent class variable" Watch "threads and inconsistent class variable" New topic
Author

threads and inconsistent class variable

Harsha Hegde
Greenhorn

Joined: Jan 12, 2009
Posts: 17

I have a code something like the below, problem is I get unexpected values out of the StringBuffer variable
Eg; i get outputs like "aabc", but i never expect 'a' to repeat twice !
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4165
    
  21

Can you show us more detail - a fully compilable, runnable example that shows your problem (as simple as possible though, please). There isn't enough information to see where the problem lies in the code you posted.


Steve
Harsha Hegde
Greenhorn

Joined: Jan 12, 2009
Posts: 17

Hi Steve,
Its a rather complicated implementation but I have something similar code, unfortunately I am not able to simulate the issue with below code, but just as a skeleton for reference
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4165
    
  21

See if you can't make the problem happen in some simple example. Showing code where it won't happen is not a help - since the problem obviously doesn't exist to be fixed. For one thing, the code you pasted doesn't use Threads, I assume from the title and location of this post that the error is occurring in a multi-threaded program. Try implementing the above code using multiple threads and see what you get.

Some things to take note though:

You call tc.sb.append("a") - using the sb variable outside a synchronized method call. Since sb is one of those objects you want to protect, it should only be called from inside a synchronized block or method.


I know this is a simple example, but you should keep the synchronized code to minimum needed to prevent inconsistent state. For example, in your code, depending on the expected behavior, you might want to shorten the parts of your code that are synchronized to just the parts that manipulate the StringBuffer and static integer. That depends on if you want all the work in one method to complete before the work in another method can begin...
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: threads and inconsistent class variable
 
Similar Threads
synchronized block
Array of Images - PLEASE HELP!
Swing application, screen resolution question
Evaluating Strings
what is synchronized singleton ?