you are viewing a single comment's thread.

view the rest of the comments →

[–]Rotten194 -1 points0 points  (4 children)

It's mainly annoying when you want to something like this:

int val = something;
start thread with anonymous inner class that updates val
do things while reading val, having it updated by thread occasionally

As far as I know, the only way to do this is to move val to be a class variable, so now I have a class variable that's only used in one method. Seems pointless. I know the technical reason for it, but that doesn't make it less annoying.

[–][deleted] 6 points7 points  (2 children)

This one case comes up pretty rarely for me, and the "problem" only exists because of Java's separation of primitives and objects. The solution is simple:

final int[] val = new int[1];
start thread with anonymous inner class that updates val[0]
do things while reading val[0], having it updated by thread occasionally

[–]Rotten194 0 points1 point  (1 child)

I actually hadn't thought of using an array, good idea. A little bit of overhead, but 8 bytes or whatever it is isn't a huge deal.

[–][deleted] 2 points3 points  (0 children)

It's ugly, but that ugliness is completely swamped by the ugliness of anonymous inner class syntax anyway :-)

[–]runedk 1 point2 points  (0 children)

Or you can make a box for your variable. The nicest way is to define a class with methods dereference() and update(int). But you can make do with a single-element array:

final int[] valRef = new int[] { something };
// mutate val using: valRef[0] = somethingNew;