Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

threads and inconsistent class variable

 
Harsha Hegde
Greenhorn
Posts: 17
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Harsha Hegde
Greenhorn
Posts: 17
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic