Hi Laurent, I'd probably do:
int newsizemin = oldcount + newitems; if (newsizemin < oldcount) { // hard overflow failure - we can't even accommodate // new items without overflowing return failure, throw exception? } int newsize = <growth algorithm computation>; if (newsize < newsizemin) { // overflow in growth algorithm computation newsize = newsizemin; ... OR ... newsize = MAX_INT; } while (true) { try { allocate newsize; break; (or return?) } catch (OOME e) { if (newsize == newsizemin) { throw e; } } newsize = newsizemin + (newsize - newsizemin) / 2; } ...jim On 4/8/15 9:34 AM, Laurent Bourgès wrote:
Jim, let's go back to concrete code: 2015-04-04 0:25 GMT+02:00 Jim Graham <james.gra...@oracle.com <mailto:james.gra...@oracle.com>>: The patch as it is will make things much better, but it may be worth "doing it right" as long as we are revisiting this algorithm and write it to deal better with the OOME/integer overflow cases. My patch is very simple and a lot better for huge paths. It is not perfect as it does not handle integer overflow (impossible case for me) nor OOME. How could I handle OOME first ? any advice ? I could try allocating a smaller array in case of OOME ? any example in JDK ? I looked at the ArrayList code and found a bit of voodoo there in the overflow code which troubled me as a potential maintainer. It's one thing to write clever code, it's another thing to write clever code that others can come along and maintain without having to fill a white board with input/output ranges and 2's complement rules. It's not like this code is going to be in an inner loop somewhere - the time for a couple of conditional checks and min/maxes will be vastly swallowed by the costs of allocation and copying data so it would be better to just write straightforward code whose overflow considerations are documented for future maintainers. (Having said that I probably wrote some pretty obtusely clever code in the Rectangle class myself... D'oh!) My general goal is to include comments with the incoming assumptions and then document how I've ruled out cases and narrowed ranges with small single-line comments as the calculations and decisions are made... Please give me hints, so I could improve the proposed webrev. Laurent