so I have an array of a lot of ints, and I am writing single bits to it everywhere to store information. Like so:
public class myclass
{
int[] bitArray;
//methods
public myclass()
{
bitArray = new int[200000000]; //200 million ints
}
public void flagBit(int arrayIndex, bitIndex)
{
/** 10000000 00000000 00000000 00000000 >>> bitIndex */
bitArray[arrayIndex] |= (0x80000000 >>> bitIndex);
}
}
Now, as you can see, that's a lot of data. So efficiency is imperative.
Anyway, I want multiple threads to be (safely) writing data to this array at once. Unfortunately in Java, you can't do the following:
public void flagBit(int arrayIndex, bitIndex)
{
/** 10000000 00000000 00000000 00000000 >>> bitIndex */
synchronized (bitArray[arrayIndex]) //wrong!!! must synchronize to object!
{
bitArray[arrayIndex] |= (0x80000000 >>> bitIndex);
}
}
So, I was wondering what the most efficient or best way to do this is? I'm aware of AtomicIntegerArray, but I believe that I can be more efficient than that. I've made an attempt at coming up with a solution and this is what I got (I haven't tested it yet though, is it valid?)
public class myclass
{
int[] bitArray;
SYNC[] indexSync;
//inner class(es)
private static final class SYNC
{
private static final boolean sync = false;
}
//methods
public myclass()
{
bitArray = new int[200000000]; //200 million ints
indexSync = new SYNC[bitArray.length];
}
public void flagBit(int arrayIndex, bitIndex)
{
/** 10000000 00000000 00000000 00000000 >>> bitIndex */
synchronized (indexSync[arrayIndex])
{
bitArray[arrayIndex] |= (0x80000000 >>> bitIndex);
}
}
}
So, is there a more efficient way to do that than the way I've posted? Does the way I posted even work? Would my way be very efficient? Thanks~