2011-12-15 13 views
17

¿Qué ocurre si AtomicInteger llega a Integer.MAX_VALUE y se incrementa?Incremento de AtomicInteger

¿El valor vuelve a cero?

+16

Puede intentarlo usted mismo fácilmente configurando un número entero al valor máximo y luego incrementándolo. – Gabe

+5

null no es un número nativo –

+7

+1 para esta pregunta! Creo que el objetivo del desbordamiento de Stack es que respondamos preguntas como esta y no hagamos que alguien se sienta mal por hacer la pregunta. El punto no es si un usuario debería o no ser capaz de "resolverlo". Ellos legítimamente necesitan ayuda y estamos aquí para brindarla. –

Respuesta

32

Vea usted mismo:

System.out.println(new AtomicInteger(Integer.MAX_VALUE).incrementAndGet()); 
System.out.println(Integer.MIN_VALUE); 

Salida:

-2147483648 
-2147483648 

parece que hace envoltura a MIN_VALUE.

6

Browing el código fuente, sólo tienen un

private volatile int value; 

y, y varios lugares, sumar o restar de ella, por ejemplo, en

public final int incrementAndGet() { 
    for (;;) { 
     int current = get(); 
     int next = current + 1; 
     if (compareAndSet(current, next)) 
     return next; 
    } 
} 

Por lo tanto, debe seguir las matemáticas enteras de Java estándar y ajustar a Integer.MIN_VALUE. Los JavaDocs para AtomicInteger no dicen nada al respecto (por lo que vi), así que supongo que este comportamiento podría cambiar en el futuro, pero eso parece extremadamente improbable.

Hay un AtomicLong si eso ayudaría.

ver también What happens when you increment an integer beyond its max value?