Create object after thread creation vs passing object on thread creation

2707 views java
-2

Is there any differences between creating object after thread creation (approach A below) and creating it in current thread and pass it to new thread (approach B)?

Approach A:

public class AppA {

    private A app;

    public void run() {
        Runnable runnable = () -> {
            this.app = new A();
        };
        Thread workerA = new Thread(runnable);
        workerA.start();
    }
}

public class A {

    private final EventDispatcher dispatcher;

    A() {
        this.dispatcher = new EventDispatcher();
    }
}

public static void main(String[] args) {
    AppA appA = new AppA();
    appA.run();
}

Approach B:

public class AppB {

    private B app;

    public void run() {
        EventDispatcher dispatcher = new EventDispatcher();
        Runnable runnable = () -> {
            this.app = new B(dispatcher);
        };
        Thread workerB = new Thread(runnable);
        workerB.start();
    }
}

public class B {

    private final EventDispatcher dispatcher;

    B(EventDispatcher dispatcher) {
        if (dispatcher == null) {
            throw new NullPointerException();
        }
        this.dispatcher = dispatcher;
    }
}

public static void main(String[] args) {
    AppB appB = new AppB();
    appB.run();
}
  • App object created in single thread.
  • app.run() called from single thread.

answered question

2 Answers

9

I believe there is no difference if you don't use that same object for something else (pass it to different thread maybe). It's like basic OOP - you should define your object in the narrowest scope where you will use it. Being a thread is no difference. So if you want to use it outside the thread - create it outside. Otherwise create it in the thread.

posted this
1

It's a matter of taste mostly. But in approach A, you have a better encapsulation. If you don't need access to the dispatcher outside of the thread, that it is more preferrable to create it inline. However if you do need access, or you create multiple threads that need a single dispatcher, injecting it through the constructor is better.

Ergo: it depends...

posted this

Have an answer?

JD

Please login first before posting an answer.