Concurrency and Java

Concurrency is a difficult-to-understand and error-prone aspect of Java, and the core of concurrency is threading. Fortunately, starting from JDK 1.5, Java provides a concurrent package that can help us handle most concurrency and asynchronous issues.

However, concepts such as ExecutorService and Executors still make it difficult to use this package. How can we abstract these concepts? How can we solve the problem with a single method? ThreadUtil was created for this purpose.

Principles

Hutool uses the GlobalThreadPool to maintain a global thread pool, and by default all asynchronous methods execute in this thread pool.

Methods

ThreadUtil.execute

Executes a thread directly in the public thread pool.

ThreadUtil.newExecutor

Obtains a new executor.

ThreadUtil.execAsync

Executes an asynchronous method.

ThreadUtil.newCompletionService

Creates a CompletionService, and submitting tasks to it using its submit method allows multiple tasks to be executed asynchronously. Finally, the take method can be called to retrieve the results in the order they are completed. If no results are available, it will block.

ThreadUtil.newCountDownLatch

Creates a CountDownLatch, which is a synchronization helper class that allows one or more threads to wait until a set of operations being performed in other threads completes.

ThreadUtil.sleep

Suspends the current thread. This is a wrapper for Thread.sleep, which returns a boolean indicating whether the thread was interrupted instead of throwing an exception.

The ThreadUtil.safeSleep method ensures that the thread is suspended for at least the specified time. This method is used in the Hutool-cron timer to ensure the accuracy of scheduled tasks.

ThreadUtil getStackTrace Methods

This section includes two methods:

  • getStackTrace: Obtains a stack trace.
  • getStackTraceElement: Obtains a stack trace element.

Other Methods

  • createThreadLocal: Creates a thread-local object.
  • interupt: Stops the thread. Calling this method will cause the thread to throw an InterruptedException exception.
  • waitForDie: Waits for the thread to die. It calls Thread.join() and ignores InterruptedException.
  • getThreads: Obtains all threads in the JVM that belong to the same group as the current thread.
  • getMainThread: Obtains the main thread of the process.