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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.