I just learned about the AtomicInteger a few days ago. Didn't realize it existed before. I haven't tried it yet. I used to simply write my own MutableInteger class. Integer has no "set" method. AtomicInteger does, so I imagine that it can now replace my MutableInteger class. My question is why do we even need AtomicInteger. Why didn't they just allow Integers to be mutable? Clearly this was on purpose and the designers seem (at least to me) hell bent on making a regular old "swap" function impossible in order to discourage it...

int swap(int& a, int& b)
{
    int temp = a;
    a = b;
    b = temp
}

I've long tried to find workarounds, but it seems to me that if you were supposed to do it, they wouldn't have made it so difficult, so I'm trying to figure out what the "correct" thinking process is. Why aren't Integers mutable and how does one write the good old "swap" method?

Recommended Answers

All 18 Replies

My question is why do we even need AtomicInteger.

It is not about mutability. An Atomic prefix suggests that its methods are sefe in the multithreaded environment without additional synchronization.

>> It is not about mutability. An Atomic prefix suggests that its methods are sefe in the multithreaded environment without additional synchronization.

That makes sense, so we would need an AtomicInteger for synchronization needs. But what about single-threaded environments? Why did they make Integer non-mutable?

> Why did they make Integer non-mutable?

Hard to say; my wild guess is to make it possible to use Integer as a key in a hashtable, etc.

Member Avatar for ztini

How are the architects to determine if you intend to single or multi-thread? That's a lot of overhead; multi-thread is therefore assumed.

public void swap(int n1, int n2) {
int temp = n2;
n2 = n1;
n1 = temp;
}

swap(1, 5); // does nothing

... but

public class IntegerSwap {
	
	private int a = 1;
	private int b = 5;
	
	public IntegerSwap() {
		print();
		swap();
		print();
	}
	
	private void swap() {
		int temp = a;
		a = b;
		b = temp;
	}
	
	private void print() {
		System.out.println("a: " + a);
		System.out.println("b: " + b);
		System.out.println();
	}
	
	public static void main(String[] args) {
		new IntegerSwap();
	}
}

That's the kind of stuff I've been doing. It just seems a little bit elaborate and might be more easily solvable if they would simply allow the Integer class to be mutable. I guess I can always simply use AtomicInteger when I need a mutable Integer and not worry about why? But there must be a reason.

Member Avatar for ztini

Its already been mentioned twice in this thread---coincidentally, it has to do with threading.

Still don't believe us? Read this.

>> Its already been mentioned twice in this thread---coincidentally, it has to do with threading. Still don't believe us?


Dude, get the chip off your shoulder. I'm just trying to get an understanding of why they designed it that way and whether I should use the AtomicInteger class for single threaded programs or whether I needed to continue writing my own classes such as the one you wrote. There's no need for the hostility. I'm not looking for a fight. If you are, please take it elsewhere. Of course I believe you. Nothing I wrote implied otherwise.

Of course, if you need to alter your Integer instances you are out of luck. You can write your own mutable integer wrapper class for use by your own objects.

If it's for thread safety and I'm out of luck if that's not an issue for me, as your link says, then I guess I'll just have to accept that and keep writing my own mutable wrapper. This is what I've always done.

Member Avatar for ztini

Dude, get the chip off your shoulder.... There's no need for the hostility. I'm not looking for a fight. If you are, please take it elsewhere. Of course I believe you.

The only one hostile is you.

Nothing I wrote implied otherwise.

...other than completely ignoring where your question was previously answered several times.

>> ...other than completely ignoring where your question was previously answered several times.

Why the AtomicInteger class is needed (synchronization/thread-safe issues) was answered. Why they required the Integer class to be immutable was answered once by you (overhead of creating two classes, though they already have the overhead of two classes anyway : AtomicInteger and Integer) prior to the "Still don't believe us" comment and once by nezachem, but with the "wild guess" qualifier, so basically once, not "several times" or even twice, and it didn't touch on whether there was a downside to using AtomicInteger as opposed to regular old Integer in single threads, nor why you need a thread-safe Integer class when you have a thread-safe AtomicInteger class.

I'm all for getting impatient with clueless thread starters who are told the same thing over and over again and completely ignore it, but you jumped the gun here.

Member Avatar for ztini

I'm all for getting impatient with clueless thread starters who are told the same thing over and over again and completely ignore it, but you jumped the gun here.

Not when you answer so clearly could of have been answered by a little due diligence on your part. Programming is about problem solving and sometimes experimentation (e.g. wrapping the Integer class). This is obviously not your first time with Java, so why come to the table without doing research?

http://www.google.com/#q=java+why+are+integers+immutable

The link from before is #1 on that above list.

Clearly you can see how easily the answer was obtained and how frustrating it is to pass this obvious piece of information to, as you say, a [non-] "clueless thread starter".

I did the research before starting the thread. I did several google searches. I've written many mutable wrapper classes to get around the problem, and I found this link and read the whole thing start to finish and learned a lot.

http://javadude.com/articles/passbyvalue.htm

But it didn't answer my question fully. I also found the link you posted here before I even started the thread.

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/mutable/MutableInt.html

I noticed that it's not part of the official Java Release. If it had been, I wouldn't have bothered posting in the first place. I'm wondering why it's on the Apache site, not the Java site. Your other link was informative, but also doesn't answer the question fully.

I'm not some noob who doesn't bother to do a google search. I ALWAYS do a google search first. I think my posting history makes it clear that I'm not some help leech. You'd have every reason to get upset if I had in fact done what you assume I did (just posted without doing any research). But your assumption is incorrect.

I didn't see anything in those threads that answers my question fully. And it still isn't answered. The question stands and the answer is far from "obvious". Since so many people have a need to write a mutable Integer class, why haven't they provided one?

Hi Vernon
I'm curious. In a single-threaded environment, apart from the "swap" method, why is it so important to have a mutable Integer class? I've gone fat dumb and happy in SmallTalk and Java for 20 years without ever feeling the need for one.

Hi Vernon
I'm curious. In a single-threaded environment, apart from the "swap" method, why is it so important to have a mutable Integer class? I've gone fat dumb and happy in SmallTalk and Java for 20 years without ever feeling the need for one.

I'm working with the ONE-NET wireless protocol. The code is written using Embedded C and runs on very small (i.e. 16K program memory, 3K RAM) microchips. The wireless packets need to be encrypted, encoded, have Cyclic Redundancy Check calculations, etc., and I'm creating a desktop application so that it's more user friendly. I need to communicate using the Serial Cable, which I already knew how to do in Java, but not C/C++, and I was familiar with Java Swing and I needed a GUI.

So I'm porting a bunch of C functions that manipulate packets (either by changing packets, adding to them, deleting from them, padding them, etc.). The swap function is just the tip of the iceberg. I have a ton of functions similar to this:

void CalcCRC(const int* const array, int** crc, int arrLength, int crcLength)
{
    // calculate the crc of the array, place in crc
}

crc is sometimes an array of 2 ints, sometimes just a plain old int, ditto with array. A nice simple port that stays as close to the C code as possible would be easiest. I find myself more and more having to dump the original C code completely and simply do it in Java from scratch. From a speed point of view, you'd never implement it in Java, but as a simulator/learning tool, Java Swing is what I know, so I'm porting C to Java. It would be really wonderful to have some easy way to mimic C behavior as far as the port goes.

Would it be a big deal to replace those pass-by-reference params with a one-element array? Just thinking...

Would it be a big deal to replace those pass-by-reference params with a one-element array? Just thinking...

Not a big deal. A little work, but not a big deal. I've been doing a lot of those workarounds and they have been working. I just wanted to know if my approach was all wrong and if there was a way to not have to work around them.

The much more difficult scenarios are these:

void Insert(int** array, int* insertThis, int position, int arraySize, int insertSize)
{
    // if array is {1,2,5,6}, insertThis is {3,4}, and position is 2, array
    // should be changed to {1,2,3,4,5,6}.
    int* newArray = malloc(6 * sizeof(int));
    // do the array copying
    *array = newArray;
}

The malloc screws everything up. In Java, with the array "length" being available, I can get rid of the last two parameters, so the call would be this:

Insert(array, insertThis, 2);

where array[] is an array of {1,2,5,6} and insertThis is an array of {3,4}. array[] will still be {1,2,5,6} when it returns since I'm creating a new array in the function and the variable in the calling function no longer "points" to the array created in the function.

I solve this by not using arrays, but instead using Collections, so I don't have to create new ones. It's also coming up quite a bit with all sorts of objects. Basically whenever I use the word "new" in the function, it never works. I find ways of making it work, but the code seems to get more and more kludgy and hence people who have only used C are asking stuff like "why is this an array, isn't this just a regular integer?"

> So I'm porting a bunch of C functions that manipulate packets

Now that's a completely different story. Did you consider JNI? From the validation and maintenance standpoint I'd prefer to have a few interface entries to the existing C code, rather than porting everything.

commented: Thanks for the tip. +13

>> Now that's a completely different story. Did you consider JNI? From the validation and maintenance standpoint I'd prefer to have a few interface entries to the existing C code, rather than porting everything.


No, I had never heard of JNI. Seems perfect for this assignment. I'll look into that, as there will be several similar projects. For this particular project, since I'm mostly done, I don't think I'll use it. I wish I had known about this before I started. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.