<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nicholas O&#39;Mahony on Medium]]></title>
        <description><![CDATA[Stories by Nicholas O&#39;Mahony on Medium]]></description>
        <link>https://medium.com/@omahonynicholas?source=rss-0094acb5dda0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eZ8FUeVjgYVdh6_o</url>
            <title>Stories by Nicholas O&amp;#39;Mahony on Medium</title>
            <link>https://medium.com/@omahonynicholas?source=rss-0094acb5dda0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 14:48:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omahonynicholas/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Java, Go or Python — Which language to multithread with?]]></title>
            <link>https://medium.com/@omahonynicholas/java-go-or-python-4fa1f57c7485?source=rss-0094acb5dda0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fa1f57c7485</guid>
            <category><![CDATA[threading]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nicholas O'Mahony]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 10:23:31 GMT</pubDate>
            <atom:updated>2024-10-20T15:44:43.009Z</atom:updated>
            <content:encoded><![CDATA[<p>This article serves to provide insight into the basics of multithreading, explore the process of multithreading with Java, Go and Python and help you decide which language to write your first multithreading programs in. The main goal of this article is to help you make this decision and does not serve as an accurate benchmark for Java, Go or Python multithreading speeds.</p><h3>What is a thread and what is a process?</h3><p>A process is in essence, a program in execution and represents an instance of a running application. Processes run independently and are isolated from other processes. Every process is allocated its own memory space</p><p>Within each process, there can be one or more threads. Threads are sometimes referred to as “lightweight processes” because they exist within processes, share the processes memory and resources. Unlike processes, threads can interact with each other and executes different parts of the overall processes tasks.</p><h3>What is multithreading?</h3><p>Most people are familiar with sequential programming, where a program completes one task before starting the next. Parallel programming allows a computer to perform multiple tasks at once. Think of sequential programming as a single mechanic changing the wheels on a car. The mechanic must remove and replace each wheel one by one. Parallel programming, however, is like a Formula 1 pit stop, where multiple mechanics work on each wheel at the same time — one team removes the old wheels while another team installs the new ones. This speeds up the whole process.</p><p>Multithreading allows your computer’s processor to execute multiple threads simultaneously. The number of threads that can run at the same time is limited by the number of CPU cores. Returning to the F1 example, if the pit crew only had eight mechanics instead of twelve, some mechanics would have to do both tasks — removing and replacing the tires — slowing down the process.</p><h3>What is merge sort and how can we multithread it?</h3><p>Merge sort implements the divide and conquer technique. It takes an array and recursively divides the array into smaller subarrays and sorts these subarrays. The steps are as follows: Divide the list recursively into two halves until it can no longer be divided. Sort: Each subarray is sorted individually. Merge: The sorted subarrays are merged back together in the sorted order, and this continues until all elements from both subarrays are merged. <a href="#_edn1">[i]</a></p><p>The process I followed to use multithreading with merge sort is as follows. When creating a subarray, if the size of the array is larger than a specified threshold, two new threads are created to sort the left side and right side of the array. The threshold is used to avoid creating excessive amounts of threads and is calculated by taking the array size and dividing it by the cores multiplied by two. Once the two halves are sorted, they are merged back into a sorted array. The merging method is single threaded but only occurs after each thread completes sorting its half of the array. This can be optimised, however that is not the goal of this article.</p><h3>How to multithread in each language and implementations</h3><p>To compare the process of multithreading with Java, Go and Python, I have written a merge sort algorithm and utilised each language’s implementation of multithreading to sort in parallel. There are several ways to implement threading in each language. In this article I have chosen the Thread class from java, the ThreadPoolExecutor for Python and Goroutines for Golang. Each program sorts the same array of 100,000 numbers and ran on my personal machine which has an 11th generation Intel i5 1135G7, 2.4GHz 8 Core CPU. I ran the programs 10 times; calculated the length of time it took to perform the sorting operation and calculated the average runtime.</p><p>The full source code for each program is available on my GitHub at this link: <a href="https://github.com/Niomahony/MultiThreadedMergeSort---Java-Go-Python">https://github.com/Niomahony/MultiThreadedMergeSort---Java-Go-Python</a></p><h3>Java</h3><p>When multithreading with Java, you can either extend the Thread class or implement the Runnable interface on your class. In my example below, I have extended Thread. Because Java does not allow multiple inheritance, you cannot extend any other classes if you extend thread but does allow you to use more Thread inbuilt methods. <a href="#_edn2">[ii]</a></p><p>The process for creating a multithreaded merge sort with Java was as follows;</p><p>- Create a constructor to hold the data for each threaded merge</p><p>- Create two objects for each half of the array</p><p>- Assign each object to a thread</p><p>- Wait for each merge sort to complete</p><p>- Merge the sorted halves</p><h3>Java implementation <a href="#_edn3">[iii]</a></h3><p>The threading portion of this code was very quick to set up. By overlooking the merge sort functionality, basic implementation of multithreading in java is quite simple for this task. We begin by using the start method on our leftSort and rightSort objects to initialise the threads.</p><pre>leftSort.start();<br>rightSort.start();</pre><p>Then use the join method. The join method is incredibly important in this scenario, as it forces the mergeSort method to wait for both threads to complete their respective tasks before proceeding to complete the final merge. If we did not implement the join method, this would cause incorrect sorting as one thread may not have completed sorting before merging.</p><pre>leftSort.join();<br>rightSort.join();</pre><p>On average, this code would perform the sorting of 100,000 numbers in 34 milliseconds.</p><pre>public class ThreadedMergeSort extends Thread {<br> private Integer[] array;<br> private int begin, end;<br> <br> public ThreadedMergeSort(Integer[] array, int begin, int end) {<br> this.array = array;<br> this.begin = begin;<br> this.end = end;<br> }<br> <br> @Override<br> public void run() {<br> int threadThreshold = array.length / (2 * Runtime.getRuntime().availableProcessors());<br> mergeSort(array, begin, end, threadThreshold);<br> }<br> <br> public static void mergeSort(Integer[] array, int begin, int end, int threadThreshold) {<br> if (begin &lt; end) {<br> int mid = (begin + end) / 2;<br> <br> if ((end — begin) &gt; threadThreshold) {<br> ThreadedMergeSort leftSort = new ThreadedMergeSort(array, begin, mid);<br> ThreadedMergeSort rightSort = new ThreadedMergeSort(array, mid + 1, end);<br> <br> leftSort.start();<br> rightSort.start();<br> <br> try {<br> leftSort.join();<br> rightSort.join();<br> } catch (InterruptedException e) {<br> e.printStackTrace();<br> }<br> } else {<br> mergeSort(array, begin, mid, threadThreshold);<br> mergeSort(array, mid + 1, end, threadThreshold);<br> }<br> <br> merge(array, begin, mid, end);<br> }<br> }</pre><h3>Golang</h3><p>Go was originally developed due to the creator’s dislike of C++. Go has very readable code and static typing, making it a great choice for those familiar with Java or C++ for implementing multithreading. Although it does not outperform C, it is preferable to many due to the shorter development times due to the lower barrier to entry that it has. <a href="#_edn4">[iv]</a><br> <br> Go makes multithreading extremely simple with its Goroutines. A Goroutine is a lightweight thread and can be initialised with the go keyword. You will see that the process for writing code for multithreading in Go is much more concise than Java. <a href="#_edn5">[v]</a></p><h3>Golang Implementation</h3><p>First, I initialise the sync.WaitGroup and add 2 to its counter. This is because I will have two Goroutines, one for each half of the array. The WaitGroup is used to track when the Goroutines have finished, once the WaitGroup wg’s counter is reduced to 0, the program is allowed to continue from the wg.Wait() function onward.</p><pre>var wg sync.WaitGroup<br> wg.Add(2)</pre><p>Now, I initialise the Goroutines which will be concurrently handling the task of sorting the array. The defer wg.Done() will reduce the WaitGroup’s counter by 1, letting the WaitGroup know that it has completed its task.</p><pre>go func() {<br> defer wg.Done()<br> mergeSort(array, begin, mid)<br> }()<br> go func() {<br> defer wg.Done()<br> mergeSort(array, mid+1, end)</pre><p>Go is incredibly light-weight, fast, and simple to set up multithreading with. It is in my opinion, ideal for learning multithreading concepts.<br> <br> Overall, Go was able to sort 100,000 numbers on average in 8 milliseconds.</p><pre>func mergeSort(array []int, begin, end int) {<br> if begin &lt; end {<br> mid := (begin + end) / 2<br> <br> if (end — begin) &gt; ThreadThreshold {<br> var wg sync.WaitGroup<br> wg.Add(2)<br> <br> go func() {<br> defer wg.Done()<br> mergeSort(array, begin, mid)<br> }()<br> go func() {<br> defer wg.Done()<br> mergeSort(array, mid+1, end)<br> }()<br> wg.Wait()<br> } else {<br> mergeSort(array, begin, mid)<br> mergeSort(array, mid+1, end)<br> }<br> <br> merge(array, begin, mid, end)<br> }<br> }</pre><h3>Python</h3><p>While python supports multithreading through its threading module, the fact of the matter is that python cannot perform parallelised multithreading due to the Global Interpreter Lock (GIL). Before writing the code for this article, I did not expect that Python would be the slowest language for multithreading. It is important to note the difference between parallel processes and parallel multithreading. The GIL prevents threads contained within one process from executing Python bytecode at the same time, causing the issue with parallel multithreading. To avoid the GIL issue, we can instead use parallel processing, however that is not the target for this article. Additionally, we can use a different python interpreter to run our program, but as the target demographic for this article is users who may be setting up multithreading for the first time, I decided against changing the interpreter and following the same algorithm that Java and Golang used. <a href="#_edn6">[vi]</a></p><p>Something to note is that Python does not have this same limitation on Input/Output (I/O) tasks. If you plan on using threads to parallelise I/O tasks, Python may be a great choice.</p><p><strong>Python Implementation</strong><br> To create new threads, I use executor.submit() with the parameters for the functions they will run.</p><pre>future1 = executor.submit(merge_sort, array, begin, mid, THREAD_THRESHOLD, executor)<br> future2 = executor.submit(merge_sort, array, mid + 1, end, THREAD_THRESHOLD, executor)</pre><p>After creating the threads, similarly to the other languages, we use .result() to wait for the threads to complete their tasks before proceeding with the rest of the merge.</p><pre>future1.result()<br>future2.result()</pre><p>When running in main, we call the ThreadPoolExecutor() with the following line:</p><pre>with ThreadPoolExecutor() as executor:<br>merge_sort(array, 0, len(array) — 1, THREAD_THRESHOLD, executor)</pre><p>Due to the limitations of the GIL in Python’s default interpreter, Python averaged a sorting time of 360ms. This is due to the fact that it is not truly running in parallel due to the GIL lock. This displays the tremendous efficiency of parallelising your code.</p><pre>from concurrent.futures import ThreadPoolExecutor<br> import time<br> import os<br> <br> <br> def merge_sort(array, begin, end, THREAD_THRESHOLD, executor):<br> if begin &lt; end:<br> mid = (begin + end) // 2<br> <br> if (end — begin) &gt; THREAD_THRESHOLD:<br> <br> future1 = executor.submit(merge_sort, array, begin, mid, THREAD_THRESHOLD, executor)<br> future2 = executor.submit(merge_sort, array, mid + 1, end, THREAD_THRESHOLD, executor)<br> <br> future1.result()<br> future2.result()<br> else:<br> merge_sort(array, begin, mid, THREAD_THRESHOLD, executor)<br> merge_sort(array, mid + 1, end, THREAD_THRESHOLD, executor)<br> <br> merge(array, begin, mid, end)</pre><h3>Conclusion:</h3><p>From this analysis into multithreading, Java, Go and Python, you have learned the basics of multithreading and techniques for setting up multithreading in each language. Every language has its own unique advantages and challenges and comparing them can be challenging.<br> <br> Java has an established, robust multithreading model with its Thread class and Runnable interface. Implementing multithreading is as simple as extending a class and calling its methods within your code. The main issue with multithreading in Java, is that you do it in Java. While multithreading is easy to complete, Java can be slower to develop multithreading programs in due to more convoluted syntax with the rest of your program and the requirement for more boilerplate code. Fortunately, the syntax and process for initialising threading is quite simple.</p><p>Python, despite its limitations with the GIL, remains a popular choice for I/O tasks where multithreading can still apply. Unfortunately, for our purposes within this article, it cannot achieve parallel multithreading without changing the interpreter.</p><p>Go’s lightweight Goroutines stand out as a clear winner in my opinion as they are easy to set up, easy to manage and can output incredibly fast sorting speeds.</p><p><strong>Average Sort Speed</strong></p><p>Java</p><p>34ms</p><p>Golang</p><p>8ms</p><p>Python</p><p>360ms</p><p>Ultimately, the decision will depend on your specific circumstances. If you are comfortable writing code in Java, setting up multithreading is a simple process. If you are performing I/O tasks, I would look towards Python. For overall ease of use and performance, Golang is perfect for building rapid multithreading programs and is especially useful for building efficient back-end code without needing to use C, C++ or C#.</p><p><a href="#_ednref1">[i]</a> <a href="https://www.geeksforgeeks.org/merge-sort/#illustration-of-merge-sort">https://www.geeksforgeeks.org/merge-sort/#illustration-of-merge-sort</a></p><p><a href="#_ednref2">[ii]</a> <a href="https://www.geeksforgeeks.org/multithreading-in-java/">https://www.geeksforgeeks.org/multithreading-in-java/</a></p><p><a href="#_ednref3">[iii]</a> <a href="https://www.javatpoint.com/multithreading-in-java">https://www.javatpoint.com/multithreading-in-java</a></p><p><a href="#_ednref4">[iv]</a> <a href="https://medium.com/geekculture/learn-go-part-1-the-beginning-723746f2e8b0">https://medium.com/geekculture/learn-go-part-1-the-beginning-723746f2e8b0</a></p><p><a href="#_ednref5">[v]</a> <a href="https://medium.com/@denniswon/goroutines-and-channels-golang-md-57dbb76d8bed">https://medium.com/@denniswon/goroutines-and-channels-golang-md-57dbb76d8bed</a></p><p><a href="#_ednref6">[vi]</a> <a href="https://xantygc.medium.com/python-and-the-never-ending-history-about-multithreading-15b625d561cb">https://xantygc.medium.com/python-and-the-never-ending-history-about-multithreading-15b625d561cb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fa1f57c7485" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>