The right thing to do in this instance is probably not to try to ask the allocator/OS how much memory is left, instead, consider reserving all the memory you need up front using APIs like initCapacity
or ensureTotalCapacity
and then use the *AssumeCapacity
or *Bounded
APIs to insert elements. This way, if there’s not enough memory left, your request will fail immediately instead of halfway through populating your data structure.
2 Likes