File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 4167
    
  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: 19655
    
  18

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: 19655
    
  18

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: 38064
    
  22
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
 
Similar Threads
Using Enums inside interface. Need to implement interface ?
Class and Object Problem
Help! With the formatting of the percent!
Value objects and encapsulation
Newbie Question : cannot resolve symbol : variable