This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one 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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript 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: 4181
    
  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: 4181
    
  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...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: threads and inconsistent class variable