Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

use of static variable

 
Paul Chamsay
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48374
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That will only work with a static variable if you are sure every sum is to be expressed in the same currency.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic