JDK-8230557 : wrong number of bits of space in use returned when BitSet#size() is called
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util
  • Affected Version: 11,13,14
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • OS: generic
  • CPU: generic
  • Submitted: 2019-08-30
  • Updated: 2019-09-05
  • Resolved: 2019-09-05
Related Reports
Relates :  
Description
A DESCRIPTION OF THE PROBLEM :
Because the return type of the method BitSet#size is int, so the method may return a negative value in some case, for example, will return -2147483648.
```
BitSet bitSet = new BitSet(Integer.MAX_VALUE);
for (int i = 0; i < Integer.MAX_VALUE - 1000; i++) {
    bitSet.set(i);
}
System.out.println(bitSet.size());
```

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
BitSet bitSet = new BitSet(Integer.MAX_VALUE);
for (int i = 0; i < Integer.MAX_VALUE - 1000; i++) {
    bitSet.set(i);
}
System.out.println(bitSet.size());

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
137438953408
ACTUAL -
-2147483648

---------- BEGIN SOURCE ----------
public class TestBitSetSize {

    public static void main(String[] args) throws Exception {

        java.util.BitSet bitSet = new java.util.BitSet(Integer.MAX_VALUE);
        for (int i = 0; i < Integer.MAX_VALUE - 1000; i++) {
            bitSet.set(i);
        }
        System.out.println(bitSet.size());
    }

}
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
change the return type int to long

FREQUENCY : always



Comments
Closing as the problem does not have a complete valid solution and a workaround can be used.
05-09-2019

The problem does not seem to have a complete valid solution. A BitSet may hold up to (Integer.MAX_VALUE + 1) bits, so size() physically cannot return all possible values. If a user really needs to get the correct number as a long, one can possibly use this workaround: BitSet bs = new BitSet(Integer.MAX_VALUE); long longSize = Integer.toUnsignedLong(bs.size()); // will be 2147483648
05-09-2019

To reproduce the issue, run the attached test case: JDK 11.0.4 - Fail JDK 13-ea - Fail JDK 14-ea - Fail
04-09-2019