DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Java Holiday Calendar 2016 (Day 14): Submitting a Task

Java Holiday Calendar 2016 (Day 14): Submitting a Task

These days, Java developers have a variety of means to execute tasks. From threads to join pools to caching, you have no shortage of options.

Per-Åke Minborg user avatar by
Per-Åke Minborg
·
Dec. 14, 16 · Tutorial
Like (8)
Save
Tweet
Share
7.02K Views

Join the DZone community and get the full member experience.

Join For Free

Image title

Today's tip is about submitting tasks. Historically, we Java developers commonly used a new Thread directly when we wanted something to be done in parallel with the current thread. These days, there are a number of other, better, and more convenient ways of getting the job done.

For the sake of simplicity, we assume that we have a task we want to run that does not return something. This can be modeled using the Runnable interface, and we can use lambdas to express our tasks.

Here are a number of alternate ways to execute a task:

public class Main {
    public static void main(String[] args) {

        // Runs in the main thread 
        helloWorld();

        // Runs in a new thread
        new Thread(Main::helloWorld).start();

        // Runs in the default fork join pool
        ForkJoinPool.commonPool().submit(Main::helloWorld);

        // Runs in the default fork join pool via a CompletableFuture
        CompletableFuture.runAsync(Main::helloWorld);

        // Runs in a custom fork join pool (with three workers)
        new ForkJoinPool(3).submit(Main::helloWorld)

        // Queues up task in a single thread executor
        Executors.newSingleThreadExecutor().execute(Main::helloWorld);

        // Caches tasks so that short lived re-occurring tasks can execute faster
        Executors.newCachedThreadPool().execute(Main::helloWorld);

        // Runs in a separate thread pool with the given delay
        Executors.newScheduledThreadPool(2).schedule(Main::helloWorld, 10, TimeUnit.MILLISECONDS);
    }

    public static void helloWorld() {
        System.out.println("Hello World greeting from " + Thread.currentThread().getName());
    }
}


This will produce the following print out:

Hello World greeting from main

Hello World greeting from Thread-0

Hello World greeting from ForkJoinPool.commonPool-worker-1

Hello World greeting from ForkJoinPool.commonPool-worker-1

Hello World greeting from ForkJoinPool-1-worker-1

Hello World greeting from pool-1-thread-1

Hello World greeting from pool-2-thread-1

Hello World greeting from pool-3-thread-1


Remember that in a real scenario, we need to shut down the custom thread pools we are creating, or else our program will not terminate properly (because there are still live threads hanging around). Closing a thread pool can be done like this:

try {
     forkJoinPool.shutdown();
     forkJoinPool.awaitTermination(1, TimeUnit.HOURS);

} catch (InterruptedException ie) {
     ie.printStackTrace();
} 


Read more on thread executing principles on DZone here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream-based ORM tool and runtime. Please check it out on GitHub.

Task (computing) Java (programming language) Calendar (Apple)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How Do the Docker Client and Docker Servers Work?
  • How To Use Terraform to Provision an AWS EC2 Instance
  • Load Balancing Pattern
  • The 12 Biggest Android App Development Trends in 2023

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: