0

In my class, I have a method that utilises the awt.Robot class, and I instantiate Robot() every time I run this method. I think this is slowing my processing down significantly though because in cases where the method is run 10000 times in a loop, I'm instantiating Robot() 10000 times instead of just once. If I can declare it as a global, that would solve my problems. I attempted:

Robot robot = new Robot();

Just under my class, but I need to throw the exception to use that line. Unfortuately I don't know how to do this without a try/catch block which I can't do outside of a method.

How can I get around this and initialize robot as a global?

eltabo
  • 3,749
  • 1
  • 21
  • 33
Nathan
  • 1,287
  • 6
  • 15
  • 32

2 Answers2

1

You could put the instantiation in a static block

 static Robot robot;
 static {
    try {
       robot = new Robot();
    catch()
    {}
    }
LhasaDad
  • 1,786
  • 1
  • 12
  • 19
  • But only if `robot` is declared `static`. If not you'd put the initialization statement in the constructor as HFOE suggests. – Hot Licks Jul 10 '14 at 02:07
  • could you explain how it improves the performance so we can learn? – Kick Buttowski Jul 10 '14 at 02:07
  • 1
    Thank you for the answer, I implemented it, but @KickButtowski there was actually no performance increase... It has to be something else then which confuses me, Ill just have to fiddle I guess. i thought it would make a difference because now we're creating the thing only once as opposed to n times. – Nathan Jul 10 '14 at 02:10
  • 1
    @KickButtowski - The OP wanted to create the Robot once vs repeatedly on each method call, for performance reasons. The above creates the Robot once. – Hot Licks Jul 10 '14 at 02:10
  • Still only iterating at 35 executions per second though when I need thousands :P – Nathan Jul 10 '14 at 02:14
1

Can you do this?

So long as you only have one of these classes, see singleton pattern. There will only be one Robot, making all calls to "yourRobotUsingMethod" use only one Robot.

By initializing your robot class in your class constructor, you can try/catch the initialization as the class is instatiated.

class YourClass {

    private Robot robot;    

    public YourClass() { 

        try {
            robot = new Robot();
        }
        catch(Exception e) {
            //Catch your exception here
        }
    }

    public void yourRobotUsingMethod() {
        //Use your robot here
        //You might want to check if robot is not null here too.
    }
}

I'm sorry if I've messed the keywords up, I've gotten used to C++'s block access levels. But you should get the idea

Sparkst3r
  • 23
  • 5