Search code examples
javathread-safetybigdecimalcompareto

BigDecimal compareTo() thread safety


I have a Java application that uses the compareTo() method of the BigDecimal class in order to classify a (big) real number, read as a string, according to its type (basically, "too big", double or float). The application reads a very large number of such strings per second, so any performance optimization is essential.

Following is an abbreviated excerpt of the code:

static final BigDecimal MAX_LONG    = new BigDecimal(Long.MAX_VALUE);
static final BigDecimal MAX_FLOAT   = new BigDecimal(Float.MAX_VALUE);
static final BigDecimal MAX_DOUBLE  = new BigDecimal(Double.MAX_VALUE);

String value = readValue(); // Read the number as a string

BigDecimal number = new BigDecimal(value);

if (number.compareTo(MAX_DOUBLE) > 0)
{
    ...
}
else if (number.compareTo(MAX_FLOAT) > 0)
{
    ...
}
else if (number.compareTo(MAX_LONG) > 0)
{
    ...
}

So, 2 questions

  1. In a multithreaded environment, is it safe to make the above comparisons (given the static fields)?
  2. Is there any thread-safe and faster way of implementing the above classification?

Solution

  • As BigDecimal is immutable it is also therefore thread-safe.

    You should also use BigDecimal.valueOf() instead of new BigDecimal() throughout, to take advantage of any caching that may be possible.