AWT event thread interruption - bad CPU loading

213 views Asked by At

When the AWT event thread is interrupted by performing the action on UI after sleep() or wait() it results in bad CPU (25-30%) loading caused by the running java process (Windows 7, JRE 1.7.0_05).

Why does it happen?

package main;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;

public class Main {

    public static void main(String[] args) {
        try {
            Main client = new Main();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    private Main() throws Exception {
        if (!SystemTray.isSupported()) {
            throw new Exception("System tray is not supported");
        }

        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("icon.png");
        Image img = ImageIO.read(is);
        is.close();

        TrayIcon icon = new TrayIcon(img, "Application");
        SystemTray tray = SystemTray.getSystemTray();

        MenuItem mi = new MenuItem("Connect");

        PopupMenu menu = new PopupMenu();
        menu.add(mi);
        icon.setPopupMenu(menu);

        mi.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    Thread.sleep(2500);
                    Thread.currentThread().interrupt();
                } catch (InterruptedException ex) {
                }
            }
        });

        try {
            tray.add(icon);
        } catch (AWTException e) {
            throw new Exception("Tray icon could not be added");
        }
    }
}
0

There are 0 answers