1

I have a class that extends JPanel and draws ~10 images on screen by overriding the paint method (using this method as I want to be able to manipulate the images as I draw each one). What I want to be able to do is have an update method in the class which I pass a list of potential image updates every frame. Here is what I have

List<BufferedImage> imageList = Collections.synchronizedList(new ArrayList());

public void update(list<String> imagePaths) {
    for (String path : imagePaths) {
        synchronized (imageList) {
            //Modify image list adding and removing buffered images
        }
    }
    repaint();
}

@Override
public void paintComponent(Graphics g) {
     synchronized (imageList) {
         g.drawImage(img, 0, 0, this);
     }
}

Currently as you can imagine it runs extremely slow due to the synchronized blocks? How can I drastically improve the performance please?

1
  • 5
    Don't paint in a sync'd block - just take a snapshot of the list at the start of the method and use that. Commented Jan 9, 2015 at 11:09

1 Answer 1

1

You're using a synchronized list, and then also synchronizing on that list when you iterate it. You'll probably see better performance by using something like a CopyOnWriteArrayList, which will always provide a consistent snapshot when iterated, and remove the synchronized blocks entirely.

Although, looking at your snippet, it's not clear to me which list is being iterated -- you have imageList and imagePaths, and I'm not sure where the actual images are retrieved from the list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.