Skip to content
Advertisement

Does runnable run() create a thread everytime I call it?

I wrote a class which I use like as follows:

EventWrapperBuilder.newWrapperBuilder().
            addSync(this::<some_method>).
            addSync(this::<some_method>).
            addSync(this::<some_method>).
            addAsync(() -> <some_method>, Duration.ofSeconds(10)).
            GET();

My code is the following:

private final List<EventWrapper> _wrappers = new ArrayList<>();

    public EventWrapperBuilder addSync(final Runnable task)
    {
        _wrappers.add(new EventWrapper(task, Duration.ZERO));
        return this;
    }

    public EventWrapperBuilder addAsync(final Runnable task, final Duration duration)
    {
        _wrappers.add(new EventWrapper(task, duration));
        return this;
    }

    /**
     * @return {@code List} of all {@code Future}
     */
    public List<Future<?>> GET()
    {
        final List<Future<?>> list = new ArrayList<>();

        for (final EventWrapper wrapper : getWrappers())
        {
            if (!wrapper.getDuration().isZero())
            {
                list.add(ThreadPoolManager.getInstance().scheduleEvent(wrapper.getTask(), wrapper.getDuration().toMillis()));
            }
            else
            {
                wrapper.getTask().run();
            }
        }

        return list;
    }

    /**
     * @param builder
     * @return {@code EventWrapperBuilder}
     */
    public EventWrapperBuilder COMBINE(final EventWrapperBuilder builder)
    {
        _wrappers.addAll(builder.getWrappers());
        return this;
    }

    /**
     * @return {@code List} of all {@code EventWrapper}
     */
    public List<EventWrapper> getWrappers()
    {
        return _wrappers;
    }

    //@formatter:off
    private static record EventWrapper (Runnable getTask, Duration getDuration) {}
    //@formatter:on

    public static EventWrapperBuilder newWrapperBuilder()
    {
        return new EventWrapperBuilder();
    }

My question is: Do I create a new thread every time I execute this if it’s instant i.e. the EventWrappers duration is zero?

I obviously know that the

list.add(ThreadPoolManager.getInstance().scheduleEvent(wrapper.getTask(), wrapper.getDuration().toMillis()));

creates a thread and execute it after the scheduled time but the

wrapper.getTask().run();

is real time without a thread right? I don’t want my code to create threads and therefore to be heavy when it executes run().

Advertisement

Answer

No, calling run() of the Runnable interface will not spawn a new thread. On the other hand, when you wrap the Runnable with a Thread class and call start() then the JVM will spawn a new thread and execute the Runnable in it’s context.

In your code, only the Async tasks will run in a separate thread since the Threadpool is managing their execution.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement