1
\$\begingroup\$

I have some code that draws sprites and and allows new ones to be added. To do this, I use 2 lists: 1 for the sprites that need to be drawn, and one for the new sprites that need to be added to the main list. I have done it this way so that new sprites can still be added in even if the main list is being drawn at that time.

I have the addSprite method synchronized with newSprites. The section for updating the main list with new sprites is also synchronized. These locks are there so that new sprites are not removed from the newSprites list before they are added to the main list.

I also thought of another option: Remove the newSprites list completely. Instead, just synchronize the main sprites list. This would work, but I am worried it could slow down the program because new sprites could not be added until drawing had completed.

Here is my current code:

List<Sprite> sprites=new ArrayList<Sprite>();
List<Sprite> newSprites=new ArrayList<Sprite>();


public void doDrawing() {

    for(Sprite s:sprites) {
        if(s.isVisible()) {
                s.draw();
        }
    }
    synchronized (newSprites) {
        if(newSprites.size()>0) {
            sprites.addAll(newSprites);
            newSprites.clear();
        }
    }
}

public void addSprite(Sprite s) {
    synchronized (newSprites) {
        newSprites.add(s);
    }

}

Is the newSprites a good idea? Should I replace this with something else? Any other advice or review is welcome as well, of course.

Note: I am not drawing an insane number of sprites, almost always (much) less than 100.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.