• Post Reply Bookmark Topic Watch Topic
  • New Topic

ThreadLocal in a calculator class

 
elvin de guzman
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
help please i'm quite new to java. Here's the code what's wrong with these?
the idea is that there is a singleton Calculator object, with a single ThreadLocal object used to hold the total.
Please help.
**
* Simple class that can be used to total numbers.
*
* The class is normally used within the following framework.
* <pre>
* Calculator c = Calculator.getCalculator() ;
* try {
* c.start() ;
*
* c.add( ... ) ; // call the add function as many times as necessary
*
* result = c.getTotal() ;
* } finally {
* c.stop() ;
* }
*</pre>
*
* This class is currently not thread safe since the member field
* total is common to all threads. Use the class ThreadLocal so that
* multiple threads can use the calculator simultaneously.
*
* Do not change any public signatures or interfaces otherwise
* the test application will break.
*/
public class Calculator {
private int total ;
private static ThreadLocal calculator = new ThreadLocal() ;
private Calculator() {
}
public Calculator getCalculator() {
return(Calculator)calculator.get() ;
}
public void start() {
total = 0 ;
}
public void add(int value) {
total += value ;
}
public int getTotal() {
return total;
}
public void stop() {
}
}
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ThreadLocal holds one arbitrary object for you. Each call to adjust the total will have to do something like:

Rather than copy that bit about getting the total and checking for null into every method, think about putting it into its own method.
Lemme know how that works!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!