r/javahelp • • Aug 13 '20

Codeless When using threads, is it better to implement runnable or extend thread?

was working with the Conucurrency API and this question came in my head

edit: i am reading the comments now

23 Upvotes

28 comments sorted by

24

u/sadjava Aug 13 '20

Runnable, unless you have a good reason to extend Thread.

1

u/[deleted] Aug 13 '20

good reasons?

8

u/Yithar Intermediate Brewer Aug 13 '20
  1. Java doesn't support multiple inheritance. You extend Thread, you're 100% locked into that.

  2. Runnable is a reusable task. It only has the work. Extending Thread binds both the work together with the thread, so it's not reusable. I'll let you in something. [ExecutorService]( https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.lang.Runnable)) doesn't take Thread objects. Why do you think that is?

1

u/[deleted] Aug 13 '20

i meant reasons for extending thread why would oracle have that for no reason then??

4

u/Yithar Intermediate Brewer Aug 13 '20

Reasons for extending Thread:
https://stackoverflow.com/a/29867068

Also, there are multiple reasons for the thread not being final, backwards compatibility being one of those reasons. Just because you can do it doesn't mean you should.
https://stackoverflow.com/a/10416110

In the codebase at work there's an old method that's specifically not final to allow Spring AOP to work but the comments say in capital letters to not override the method.

1

u/[deleted] Aug 13 '20

thanks man

1

u/[deleted] Aug 13 '20

Not much else to say...

-5

u/[deleted] Aug 13 '20

Secret option three, don't do either.

1

u/[deleted] Aug 13 '20

is this a meme or something?

1

u/[deleted] Aug 13 '20

Don’t think so; it’s just something I say when given two options and there’s at least a third.

2

u/[deleted] Aug 13 '20

ok

5

u/sadjava Aug 13 '20

There is a saying derived from another problem with regex:

Some people, when confronted with a problem think: “I know, I’ll add threads.” And now, they have n-cores problems.

9

u/[deleted] Aug 13 '20

There's a few options, but i'd say:

- almost never extend thread.

- if your class starts a thread itself; don't implement Runnable (instead use a method reference of lambda in the constructor of Thread.)

- if your class is some logic that can be worked on a thread, implement runnable and construct the thread outside of it.

- Finally Consider using a task execution framework instead of the above.

2

u/[deleted] Aug 13 '20

a task execution framework

is that like the Fork/Join framework?

2

u/[deleted] Aug 13 '20

Yes; or the older thread executor pool stuff.

1

u/[deleted] Aug 13 '20

ok thanks dude, i need to learn that framework F/J anyways

2

u/AudioManiac Aug 13 '20

if your class starts a thread itself; don't implement Runnable (instead use a method reference of lambda in the constructor of Thread.)

Can you elaborate on this? I'm not sure what you mean by it?

3

u/[deleted] Aug 13 '20

for example:

public final class MessagePump {
    public void startPump() {
         this.thread = new Thread(this::run);
    }

    private void run() {
         while(active) {
             ...
         }
    }
}

So in that case your object is a MessagePump; and effectively it stands alone. Because of the 'startPump' function. Because of that, you don't want to allow the class to be passed to say a threaded execution, because its designed to be a thread.

i.e: (new ForkJoinPool()).execute(new MessagePump(...));

Whilst that might work - its not really how a task framework is to be used.

So by not implementing Runnable you keep the interface of the MessagePump minimal and correct - and force the user to use it correctly.

I'm sure some will look at that class (MessagePump) and complain that it is doing two things, but it works as an example.

3

u/EzehMilton Aug 13 '20

Runnable, using Lambda - A lot easier to read too.

0

u/[deleted] Aug 13 '20

lambda expressions, can you show me what you mean with code

1

u/Yithar Intermediate Brewer Aug 14 '20

I apologize if this comes off as rude, but you do kind of need to get good at googling things as a software developer.
https://lmgtfy.com/?q=java+lambda+expression
https://lmgtfy.com/?q=runnable+lambda+expression

1

u/[deleted] Aug 14 '20

no , ik u need to google things alot

1

u/[deleted] Aug 14 '20

ik what lambda expressions are lol

1

u/Yithar Intermediate Brewer Aug 14 '20

I posted both links because your statement wasn't clear on that. In that case, the second link I posted is still relevant. The first search result to https://alvinalexander.com/ shows code for Runnable using lambda expressions.

1

u/[deleted] Aug 14 '20

yes i saw it already, ive done stuff like that b4 with AWT

1

u/1Kisha Aug 13 '20

Implementing runnable would be better choice cause you got option to extend as well but not in case of extending the thread.

1

u/[deleted] Aug 13 '20

cause you got option to extend as well

alright thanks dude

1

u/[deleted] Aug 14 '20

I usually prefer not to use Thread or Runnable, but use the ExecutorService API:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyWorkTask {

  private ExecutorService service;
  private Future<?> task;

  public void start() {
    this.service = Executors.newSingleThreadExecutor();
    this.task = service.submit(this::doWork);
  }

  public void stop() {
    if (this.task != null)
      this.task.cancel(true);
    if (this.service != null)
      this.service.shutdown();
  }

  private void doWork() {
    // do work
  }
}

This example is for one task running in a separate thread. This way you can store data for your thread, have a clear situation when you start or stop.

Depending on your application you might want to pass the ExecutorService in a constructor, or maybe have another class initialize the ExecutorService and Tasks and then only have the doWork() method here.

Many ways to due to, but starting your own Threads, TimerTasks, etc. should be a think of the past, since the ExecutorService API takes care of all the low level stuff.