1

I've two JSP files, where each one is accessed by different PCs.

In the first one, I'm creating an object of type Integer:

Integer var = 0;
application.setAttribute("name_var", var);

At the second one, I'm getting the attribute created before:

var = (Integer) application.getAttribute("name_var");

At this point everything is fine. I've my value at the second JSP, in a different PC.

Since Java is pass-by-value, where that values are references (Is Java "pass-by-reference" or "pass-by-value"?), I guess I've the same instance in both the JSP files (being visited by different PCs).

So now, When I'm modifying my var value, and It doesn't appear modified in the other side, I don't understand why.

var++;
Output (in the JSP where the attribute was set): 0 (still)

Can anyone explain me what is happening? Have I to update the object with a setAttribute each time I modify its value?

Thank you in advance

Community
  • 1
  • 1
Btc Sources
  • 1,912
  • 2
  • 30
  • 58

2 Answers2

1

Instead of just var++, you need to set the changed value back to the application attribute:

application.setAttribute("name_var", ++var);

The reason is autoboxing and immutability of Integer objects. When you say var++, java unboxes the Integer into a primitive int and increments that. But the result doesn't go into the attribute.

gknicker
  • 5,509
  • 2
  • 25
  • 41
1

var++ doesn't change the internal state of the Integer instance stored in the application. An Integer is immutable. Its state never changes.

The operation is equivalent to

int tmp = var.intValue();
tmp = tmp + 1;
var = Integer.valueOf(i);

So var now references another Integer instance than the one stored in the application.

The alternative is to store the new value in the application again, or to store a thread-safe, mutable value in the application:

AtomicInteger var = new AtomicInteger(0);
application.setAttribute("name_var", var);
...
var.incrementAndGet();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255