0

I have such code in my application which I want to run in background:

import java.awt.*;
import java.awt.datatransfer.*;

class Main extends Thread implements ClipboardOwner {

    private Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();

    public void run() {
      Transferable trans = sysClip.getContents(this);
      regainOwnership(trans);
      System.out.println("Listening to board...");
      while (true) { }
    }

    public static void main(String[] args) {
      Main b = new Main();
      b.start();
    }
  //............

It listens for Ctrl+C and prints the content of clipboard once this key combination is pressed. However, it makes CPU run 99% all the time. If I remove while (true) { } then the application will just stop in a second.

I tried to launch it as java -jar myapp.jar & but the result was the same. And it would be the same on Windows I guess, although I care about Linux for now.

What do I do about that?

Incerteza
  • 32,326
  • 47
  • 154
  • 261

2 Answers2

3

You have a thread running an infinite loop. That's exactly the sort of thing that will use 100% of your CPU for nothing. If nothing else, putting a couple second Thread.sleep() in the loop will bring the CPU usage down.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

You should avoid using eternal loops to check if a variable has changed, but rather use a listener. To be more precise, a FlavorListener will allow you to execute code when the clipboard has changed.

It would be something like this:

    Toolkit.getDefaultToolkit().getSystemClipboard().addFlavorListener(
        new FlavorListener() { 
        @Override 
        public void flavorsChanged(FlavorEvent e) { 
            System.out.println("Clipboard contents: " + e.toString()); 
        } 
    }); 
Community
  • 1
  • 1
Luke
  • 409
  • 3
  • 12