Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Runnable accessing a class's object

Tags:

java

runnable

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);
    }
like image 572
darksky Avatar asked Feb 10 '23 23:02

darksky


1 Answers

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.

like image 140
user253751 Avatar answered Feb 13 '23 21:02

user253751