import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;
import java.io.File;

public class WeakColorTest {
    public static void main(String[] args) throws Exception {
        BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); // This image is full-black.
        VolatileImage image = GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getDefaultScreenDevice().getDefaultConfiguration().createCompatibleVolatileImage(100, 100);
        Graphics2D g = image.createGraphics();

        // Create a new Color - we want it to be collected later.
        g.setColor(new Color(255, 0, 0));

        g.fillRect(0, 0, 100, 100);

        // Change color to prevent Graphics from keeping our Color alive.
        g.setColor(Color.BLACK);

        // Fire GC. Now the Color was collected, and BufferedContext thinks that we have no current paint.
        System.gc(); // Comment this line and see that now blit succeeds - our snapshot image is now black.

        // This blit fails on Metal due to paint not being properly reset.
        // We see the red background instead of a black image.
        g.drawImage(bi, 0, 0, null);
        g.dispose();

        ImageIO.write(image.getSnapshot(), "PNG", new File("snapshot.png"));
    }
}
