aspose file tools
The moose likes Threads and Synchronization and the fly likes ThreadLocal in a calculator class Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "ThreadLocal in a calculator class" Watch "ThreadLocal in a calculator class" New topic
Author

ThreadLocal in a calculator class

elvin de guzman
Greenhorn

Joined: Dec 11, 2003
Posts: 1
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

Joined: Jan 29, 2003
Posts: 8791
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!


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://zeroturnaround.com/jrebel/download
 
subject: ThreadLocal in a calculator class
 
Similar Threads
ConcurrentHapMap size not as expected when put done using Multiple Threads
wait(), notify, notifyAll() doubt
question about using localthread in hibernate?
where i need to use the ThreadLocal in Real world?
What is ThreadLocal?