2

Looking at the Java8 doc for OptionalInt, it seems that OptionalInt cannot be reused by setting a new value or emptying the existing value. Moreover the JavaDoc shows only two ways of initializing an OptionalInt by calling static methods - looks like an immutable object.

Is it really not reusable?

Imagine a batch processing, where the data to process consists of an int primitive, which is can be optional. For each row (let it be millions of rows) a new OptionalInt object would have to be created. The goal is to avoid unnecessary object instantiation and the additional garbage collection. So I rather would have to reimplement it myself and avoid the Java8 utility class OptionalInt?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
gclaussn
  • 1,736
  • 16
  • 19
  • 3
    If you have to handle millions of rows, the performance problems you'll have will most likely be with IO, not with OptionalInt instances. The JVM is very fast at dealing with short-term lived objects. Avoid pre-optmization. – JB Nizet Oct 11 '15 at 11:33

2 Answers2

5

OptionalInt is immutable. This means that, once the object has been created, its state cannot be modified.

An OptionalInt is either created by calling the static factories empty() or of(value). Then, there are several methods to get the optional value (getAsInt()), use a default value if no value is present (orElse(other)), etc., but you will find no methods to update the current value or empty it.

In your example of batch processing, immutability is actually something you want to have because it really helps building concurrent applications. When you are processing millions of row, you want that process to be faster by making use of multi-threading. Handling mutable objects in a multi-threaded environment is very hard to do right.

You should not worry too much about the new objects that are created. Typically, they are short-lived and the JVM handles that kind of objects very well. Actually, take a look at this question: immutable objects are preferable for the garbage collector.

Community
  • 1
  • 1
Tunaki
  • 132,869
  • 46
  • 340
  • 423
1

Optional is of course not a good intermediate container for bulk processing. It's ok only to represent the final result. If you want to bulk process primitive values, consider using IntStreal.reduce or its friends.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334