In this article we will see on how to use practical and simple Java threads to perform parallel processing in your application. The robust Java platform offers us another bonus feature when we deal with parallel processing. In this article we present a practical use of Threads in Java, with the goal of working in parallel, also known as concurrent programming.
Threads in Java
Before starting the practical explanation of Thread, understand that these are subdivisions of the processes. Each process has several threads (lines of instructions), so we can share parts of our process (Java program) to work in parallel.
The threads are in our day-to-day, in all the experiments in our computer. When we are listening to music and looking at facebook at the same time, we are conducting a parallel processing, even if it is transparent to the user.
In a Java program we want to run two or more threads at the same time, ie, two or more internal procedures of the program at the same time. To simplify the explanation of threads in Java, let’s take a practical example.
Imagine you have one procedure that consumes a lot of processor time, let’s assume the following example of a calculation that makes queries to a Web Service:
Procedure without common thread
public void CalculateTotalReceived () { //Receives about 70 thousand records. List<ReceiptHistoryreceived> received = getListOfReceipts(); Integer sum = 0; for (h1 ReceiptHistoryreceived: received) { sum = sum + received.getReceivedValue (); } Integer taxPercentage = getCurrentAdjustmentValueFromWebService(); sum = sum + ((taxPercentage/100) * sum); totalValueReturnToWebService(sum); }
The above procedure seems simple (in fact it is simple), a list with about 70 thousand records are received. For each record value and sum is picked up. After this, capture a value for adjustment percentage (captured from a WebService which can take time to respond), and recalculates the value added. Finally returns the result via WebService.
Note here that, the procedure here would take few minutes, and will not return anything to the user and just an internal communication between Web Services keep happening. We can not stop the application to perform the above procedure. Well imagine if you’re doing a simple registration and have to wait for about 5 minutes to complete the above processing.
The solution then is to make this procedure to run concurrently, ie while the user is performing the record, the above procedure is also performed, and probably when he has finished the registration, the above procedure has also ended.
In the code below we use the same code, but using the concept of threads. We will create a thread for a specific block of code through the class java.lang.Thread.
There is an interface called Runnable that has a run method. Inside the run method, you should include the procedures you want to run in parallel, so we put all the above code within a method run. Runnable is just a contract, we need some class that implements and does the work of “parallelization”, and that class is the Thread class.
Using Thread
public void CalculateTotalReceived () { new Thread () { @ Override public void run () { // Receives about 70thousand records. List<ReceiptHistoryreceived> received = getListOfReceipts(); Integer sum = 0; for (h1 ReceiptHistoryreceived: received) { sum = sum + received.getReceivedValue (); } Integer taxPercentage = getCurrentAdjustmentValueFromWebService(); sum = sum + ((taxPercentage/100) * sum); totalValueReturnToWebService(sum); } }.start (); }
When we do “.Start ();” we are already starting the parallel processing, and releasing the program to be executed by any other thread. So assimilating the following idea:
- If you want your program does not “lock the user” for that particular procedure or is taking a long time to execute, then use Thread.
- If you want your class to be processed in parallel, but it already extends another, you can choose to implement the Runnable, which is the standard interface for Thread. For best practice, implement Runnable instead of extending Thread.
- Pay attention to another very important point: The programmer has no control over the processor scheduler. This means that the processes are executed in parallel, you have no way of knowing what is execution order of these.
In the example below we put 2 counters to run in parallel, you will realize that the results may differ each time you run, or even from computer to computer.
Test Counters with Thread
package net.javabeat; public class MyTest { static int i = 0; public static void main (String [] args) { new Thread (t1). start (); new Thread (t2). start (); } private static void countMe (String name) { i++; System.out.println ( "Current Counter is:" + i + ", updated by:" + name); } private static Runnable t1 = new Runnable () { public void run () { try { for (int i = 0;i <5; i ++) { countMe ( "t1" ); } } catch (Exception e) {} } }; private static Runnable t2 = new Runnable () { public void run () { try { for (int i = 0;i <5; i++) { countMe ( "t2" ); } } catch (Exception e) {} } }; }
I’ll leave it up to you to test the above code and see what the outcome, because each computer may have a different order of execution,hence the ouptut may vary.
Summary
Use the resources of concurrent programming with care and only in the moments that really need it. Do not use Runnable in all codes thinking that your program will be faster, however, a process may need other resources. So carefully review the need to use this powerful feature . If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook.