Extremely Serious

Category: Modular Java (Page 2 of 2)

ThreadPoolExecutor with ArrayBlockingQueue and Custom Thread Name

Create an implementation of ThreadFactory to create a thread with custom name for ThreadPoolExecutor as follows:

class MyThreadFactory implements ThreadFactory {
    private AtomicLong threadCounter;

    private MyThreadFactory() {
        threadCounter = new AtomicLong();
    }

    @Override
    public Thread newThread(Runnable runnable) {
        var thread=new Thread(runnable);
        thread.setName(String.join("-","my-thread",
                String.valueOf(threadCounter.incrementAndGet())));
        return thread;
    }
}

The preceding class will generate a thread with the name starting with my-thread. Use the instance of this class in constructing the ThreadPoolExecutor as follows:

var executor = new ThreadPoolExecutor(2, 4, 60L, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(100), new MyThreadFactory(), 
        new ThreadPoolExecutor.CallerRunsPolicy());

The preceding declaration creates an instance of ThreadPoolExecutor with 2 core threads, 4 maximum threads, 60 seconds keep alive and supports 100 items in the queue. The queue size is defined by the instance of ArrayBlockingQueue class.

Start all the core threads as follows:

executor.prestartAllCoreThreads();

Using a profiling tool we can search for all the threads whose names starts with my-thread like the following screenshot:

Don't forget to call any shutdown/terminate methods when done using the executor.

Getting a Resource using ModuleLayer

If the resource and the module are known, we can use the ModuleLayer to access it like the following snippet.

ModuleLayer.boot().findModule(<MODULE_NAME>).ifPresent(___module -> {
    try {
        var modResource = ___module.getResourceAsStream(<RESOURCE_NAME>);
    } catch (IOException e) {
        e.printStackTrace();
    }
});

Where:

MODULE_NAME -> the name of the module that has the resource.
RESOURCE_NAME -> the resource of interest.

Sample Usage of Java 9 Flow (Reactive Stream) API

Reactive stream is gaining traction in the mainstream programming and java has its own implementation via the Flow API. Popular reactive stream implementations are RxJava, Reactor and Akka.

import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
import java.util.stream.IntStream;

public class Main {

    /**
     * Sample subscriber implementation.
     */
    public static class Subscriber implements Flow.Subscriber<Integer> {

        /**
         * Holds an instance of Flow.Subscription instance so that we can request what we can handle.
         */
        private Flow.Subscription subscription;

        /**
         * Tracks if the publisher was closed.
         */
        private boolean isDone;

        /**
         * Triggered on the initial subscription.
         * @param subscription An instance of Flow.Subscription.
         */
        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            System.out.println("Subscribed");
            this.subscription = subscription;
            this.subscription.request(1);
        }

        /**
         * Do the actual processing.
         * @param item The actual item currently being processed.
         */
        @Override
        public void onNext(Integer item) {
            System.out.println("Processing " + item);
            this.subscription.request(1);
        }

        /**
         * Holds how to handle error.
         * @param throwable An instance of Throwable.
         */
        @Override
        public void onError(Throwable throwable) {
            throwable.printStackTrace();
        }

        /**
         * Called with the publisher was closed or completed.
         */
        @Override
        public void onComplete() {
            System.out.println("Processing done.");
            isDone = true;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        
        //The publisher of the data.
        SubmissionPublisher<Integer> publisher = new SubmissionPublisher<>();

        //The sample subscriber implementation.
        Subscriber subscriber = new Subscriber();
        
        //Register a subscriber.
        publisher.subscribe(subscriber);

        //The sample stream to process.
        var intData = IntStream.rangeClosed(1, 10);

        //Publish the stream data. 
        intData.forEach(publisher::submit);

        //The publisher is done.
        publisher.close();

        //Since this is processing is asynchronous wait for everything to be processed. 
        while(!subscriber.isDone) {
            Thread.sleep(10);
        }
        
        System.out.println("Done");
    }
}

Using JShell for testing an API

Java 9 was released and JShell (i.e. The REPL of Java) is now real and we can use this to test an API.

For example if we want to check the reverse function StringUtils from the commons-lang3-3.1.jar.
1.) Using windows terminal (i.e. cmd command).
2.) From this directory execute to following command jshell command.
jshell --class-path .\commons-lang3-3.1.jar
Expect to see something similar to the following:
Welcome to JShell -- Version 9.0.1
For an introduction type: /help intro

jshell>
3.) From the jshell prompt import the class org.apache.commons.lang3.StringUtils just like we normally do in java and then press enter.
e.g.
jshell> import org.apache.commons.lang3.StringUtils
4.) To optionally check all the imported classes on the current jshell session we can use /imports command.
e.g.
jshell> /imports
The sample output would be:
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.nio.file.*
|    import java.util.*
|    import java.util.concurrent.*
|    import java.util.function.*
|    import java.util.prefs.*
|    import java.util.regex.*
|    import java.util.stream.*
|    import org.apache.commons.lang3.StringUtils
5.) Since we know that the StringUtils class was already loaded. We can now execute its reverse function.
e.g.
jshell> StringUtils.reverse("abcde")
The output must be:
$2 ==> "edcba"
Note: if you want to exit jshell execute the /exit command.
Newer posts »