Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java ThreadFactory

farenda 2015-10-15 0

Problem:

How to use Java Threadfactory to create custom threads and hide thread configuration details? In this post we’ll show how to create daemon threads with custom priorities.

Solution:

Java 5 came with excellent java.util.concurrent, which contains ThreadFactory interface with only one method:

  • Thread newThread(Runnable r)
    Constructs a new Thread.

Of course the package ships many ready-to-use implementations and ThreadFactory is no different. java.util.concurrent.Executors has method defaultThreadFactory() that provides convenient implementation.

In this post we’re going to implement own ThreadFactory that creates daemon threads with given priorities. Before using the given priority we have to validate that it has acceptable value for Java Threads:

package com.farenda.java.util.concurrent;

import java.util.concurrent.ThreadFactory;

import static java.lang.Thread.MAX_PRIORITY;
import static java.lang.Thread.MIN_PRIORITY;

public class ThreadFactoryExample {

    private static class EchoJob implements Runnable {
        private static int njobs = 0;
        private final int id = ++njobs;

        @Override
        public void run() {
            System.out.println("Running job: " + id);
        }
    }

    private static class PrioritizedDaemonThreadFactory implements ThreadFactory {
        private static final String INVALID_PRIORITY_MESSAGE
                = "Priority must be between " + MIN_PRIORITY
                + " and " + MAX_PRIORITY + ". Was: ";
        private final int priority;

        public PrioritizedDaemonThreadFactory(int priority) {
            validatePriority(priority);
            this.priority = priority;
        }

        private void validatePriority(int priority) {
            if (priority < MIN_PRIORITY || MAX_PRIORITY < priority) {
                throw new IllegalArgumentException(
                        INVALID_PRIORITY_MESSAGE + priority);
            }
        }

        @Override
        public Thread newThread(Runnable job) {
            System.out.println("Creating a new thread");
            Thread thread = new Thread(job);
            thread.setDaemon(true);
            thread.setPriority(priority);
            return thread;
        }
    }

    public static void main(String[] args) {
        System.out.println("Creating ThreadFactory with invalid priority:");
        try {
            new PrioritizedDaemonThreadFactory(0);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage() + "\n");
        }

        System.out.println("Creating ThreadFactory producing slow daemons");
        ThreadFactory slowDaemons = new PrioritizedDaemonThreadFactory(MIN_PRIORITY);

        runJobs(slowDaemons);

        System.out.println("End of program.");
    }

    private static void runJobs(ThreadFactory threadFactory) {
        System.out.println("Starting jobs:");
        for (int i = 0; i < 5; ++i) {
            threadFactory.newThread(new EchoJob()).start();
        }
    }
}

Using a Factory to create a new threads separates consumer of the threads (here runJobs(ThreadFactory)) from details of its creation (implementation of the factory). Now the type of created threads can be easily changed, for example one can use Executors.defaultThreadFactory().

Here’s the output of running the above code:

Creating ThreadFactory with invalid priority:
Priority must be between 1 and 10. Was: 0

Creating ThreadFactory producing slow daemons
Starting jobs:
Creating a new thread
Creating a new thread
Running job: 1
Creating a new thread
Running job: 2
Creating a new thread
Running job: 3
Creating a new thread
Running job: 4
End of program.

As can be seen in the output, the program ends before running the last job (5), which is perfectly fine for daemon threads (see Java daemon thread for more details).

Share with the World!
Categories Java Tags java, java-concurrency
Previous: Java Single Thread Executor
Next: Java Callable Example

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok