Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Listener with Threads

Say I have an Object Foo that wants to get informed by several running instances of a Thread using a listener interface. E.g.

The interface:

public interface ThreadListener {
   public void onNewData(String blabla);
}

The class Foo:

public class Foo implements ThreadListener {
   public Foo() {
      FooThread th1 = new FooThread();
      FooThread th2 = new FooThread();
      ...

      th1.addListener(this);
      th2.addListener(this);
      ...

      th1.start();
      th2.start();
      ...
   }

   @Override
   public void onNewData(String blabla) {
     ...
   }
}

The Thread:

public FooThread extends Thread {
   private ThreadListener listener = null;

   public void addListener(ThreadListener listener) {
      this.listener = listener;
   }

   private void informListener() {
      if (listener != null) {
         listener.onNewData("Hello from " + this.getName());
      }
   }

   @Override
   public void run() {
     super.run();

     while(true) {
        informListener();
     }
   }
}

In the worst case onNewData(..) is invoked by several threads at the same time. What will happen with Foo? Is it going to crash or not?

like image 525
Yannick Wald Avatar asked Dec 10 '25 14:12

Yannick Wald


1 Answers

  • Your Foo class has no state (fields), so unless it uses external shared resources (e.g. files...) it is thread safe
  • Starting thread from a constructor is generally a bad idea although in the case of a state-less object, I suppose it is fine
  • if onNewData does not access shared data it will work as expected, if it does, the outcome will depend on how the method is implemented.
like image 103
assylias Avatar answered Dec 13 '25 03:12

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!