What method do you use for coming up with a numbering system for images when adding them to a tracker? Right now I’m trying this hybrid Dewey Decimal system, which ends up having me looking up and down my code to make sure an ID isn’t taken yet. Then it occurred to me that if I had a pointer, I could use that as the ID, but couldn’t find a method that gave me that. Any ideas?
Increment a long
Eclipse says it needs to be an int instead, but gave me a great idea of writing a small counting procedure:
public int nextID() {
nextInt ++;
return nextInt;
}
Why I didn’t think of this before… I don’t know.
If you ever plan on even reading that counter from multiple threads, you’d best make that an AtomicLong.
Are you saying that if one of my threads needs to use the MediaTracker, this method could pose a problem? Even if I’m 100% sure that all other treads are done using this method?
Just making nextID() synchronized is also fine if nextInt is private. If it’s readable, it also should be volatile or you have no guarantees about not reading a stale id if it’s updated by another thread. You cannot be sure what’s “done” if you haven’t synchronized, because of reordering.
The Atomic* classes are convenient for ensuring everyone gets a consistent view, and they do it a bit more efficiently than using synchronized blocks. If you have a counter and you have multiple threads using it, make it atomic, full stop.
Just to scare you a little more: if you don’t synchronize access to a long or double, it’s possible to read a number where only half the bits are new and the other half are old, making your counter wildly off. It’s called “word tearing”, and the JVM allows it to happen for those two datatypes.
So an atomic variable basically has a built in Mutex?
You can treat it like it has a mutex. What it actually has is a volatile value internally that it updates with intrinsic compareAndSwap operations in sun.misc.unsafe. If the CPU doesn’t have CAS operations, it’ll fall back to a mutex.
I’m not sure this will be an actual problem for you. I’d be very surprised if you had multiple Threads trying to get at a single MediaTracker, seeing as they’re just a means to an end to get Images. Are you multi-threading your image loading?
EDIT: Nevermind. 8)