In Java, how/when are variables disposed of? Are they?
First, lets get something clear. In Java, there are things called variables, and there are things called objects. Variables and objects are not the same thing.
A variable in Java is always part of something else:
An local variable is part of the state of a method call. It gets disposed of when it goes out of scope. That typically means when the method call ends and the method call's stack frame gets popped from the call stack.
An instance variable (or field or attribute) is part of an object. It gets disposed of when the object gets disposed of.
A static variable (or class variable) is part of a class, and will only get disposed of if the class is unloaded.
In your example, all of the variables are local variables, and will be "disposed of" when the current call to the run()
method returns (or terminates due to an exception).
Would bringing those variables (lastTime, unprocessed, ticks, etc.) into a higher level of scope make the program run better/more efficiently--to a place where they are not created and used multiple times per second?
It wouldn't help. The incremental cost of creating or disposing of a local variable is ZERO1. And the cost of using a local variable is (if anything) less that the cost of using an instance variable. The only cost might be in initializing it, but you would incur that cost anyway; e.g. in re-initializing an instance variable on each method call.
Indeed, turning local variables into instance variables could actually be a bad thing. It would mean that the method now uses object variables to represent its state, making it non-reentrant. (It is unclear whether that matters here. It depends on whether the run()
method is used in a way that requires it to be reentrant ... and typically that is not the case.)
1 - That's slightly over-simplified. If you have a large enough number of local variables and/or a deeply recursive method, then it is possible that you will need to use a larger-than-normal thread stack size. That extra memory usage would be a cost.