aspose file tools*
The moose likes Beginning Java and the fly likes use of static variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "use of static variable" Watch "use of static variable" New topic
Author

use of static variable

Paul Chamsay
Ranch Hand

Joined: Feb 06, 2009
Posts: 36
Hi everyone,

I would like to ask if it is a 'good' practice to use a static variable (currency) for something like this?

Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

In a single threaded environment, that would be safe, but if you plan on allowing your application to run with multiple threads it is no longer safe. From the NumberFormat API:
Synchronization

Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.


Steve
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

Also, don't make it public. If you do, other code can modify your NumberFormat object without you knowing. The results may be devastating in some applications.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

Steve Luke wrote:In a single threaded environment, that would be safe, but if you plan on allowing your application to run with multiple threads it is no longer safe. From the NumberFormat API:
Synchronization

Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.


ThreadLocal can be quite useful in multi-threaded environments:
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38881
    
  23
That will only work with a static variable if you are sure every sum is to be expressed in the same currency.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: use of static variable