Hello, I have a problem with thread safety on this block of code. Synchronized just seems to be ignored… I am using a static variable to count the calls to it, and it’s reaching 2 most of the times, while it should never go over 1. Am I doing something incredibly and terribly wrong or is this a bug? I also tried making the whole method synchronized, and it won’t change anything.
//This method looks for an available model id. If none is found, it tries to discard an expendable model to make room.
//If no expendable model, it returns -1 as an error code, and the model won't be loaded.
public int createInFirstAvailableID(String fileName){
int i=0;
synchronized (this){
ModelsManager.count++;
System.out.println("Istances: "+ModelsManager.count);
while(i<Configuration.getMaxModelCount() && models[i++]!=null);
if(i<Configuration.getMaxModelCount()){ //I found an usable id
System.out.println("Id found: "+ (i-1)+" for "+fileName);
models[--i]=new Model3D(fileName);
System.out.println("Model created: "+ i+" for "+fileName);
ModelsManager.count--;
return i;
}else{ //No available id, need to discard an expendable texture
//if I get here it means all ids are taken, pointless to check on models[] again, just free up one with 0 istances
i=0;
while(i<Configuration.getMaxModelCount()){
if(instanceCount[i]==0){ //Found one to discard
models[i].release();
models[i]=new Model3D(fileName);
ModelsManager.count--;
return i;
}else{
i++;
}
}
ModelsManager.count--;
return -1;
}
}
}
Thanks…
