I have a class that has a job that runs every 10 seconds as shown in the code block below. In Runnable() however, I cannot access the class's objects. I am assuming it has to do with thread-safety in Java.
If I implement Runnable, I will then have to provide a run()
function. I don't really want to do this. What I want to do is have the class have its own normal functions, but just have this job that runs every X seconds within it, and accesses the class's LinkedList. My run below is contained in the the scheduleAtFixedRate
, and not in the class itself.
Any ideas?
public class MyClass {
private volatile LinkedList<String> words;
public MyClass() {
this.words = new LinkedList<String>();
this.cleanup();
}
public void cleanup() {
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// can't access this.words here
}
}
}, 0, 10, TimeUnit.SECONDS);
}
Use MyClass.this.words
, or just words
.
The this
reference to an outer class X
can be accessed using X.this
. This does not work if the outer class is an anonymous class (which in this case it isn't).
Alternatively, you can use just words
rather than something.words
- like with this
, the compiler will use X.this
automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With