Showing posts with label Java Multithreading. Show all posts
Showing posts with label Java Multithreading. Show all posts

Wednesday, May 17, 2023

Quiz yourself: Crossing Java’s CyclicBarrier in a multithreaded environment

Oracle Java Certification, Core Java, Oracle Java Learning, Java Prep, Oracle Java Learning, Oracle Java Quiz


Given the following class

public class Escape {
  static class Task implements Runnable {
    int i;
    CyclicBarrier cb;
    public Task(int i, CyclicBarrier cb) {this.i=i; this.cb=cb;}
    @Override
    public void run() {
      try {
        cb.await();
      } catch (Exception e) {}
      System.out.printf("Task %d executed%n", i);
    }
  }
  public static void main(String[] args) {
    final ExecutorService es = Executors.newFixedThreadPool(2);
    final CyclicBarrier cb = new CyclicBarrier(3);
    IntStream
      .rangeClosed(1, 10)
      .mapToObj(i -> new Task(i, cb))
      .forEach(t -> es.execute(t));
    es.shutdown();
  }
}

What is the result? Choose one.

A. Nothing is printed.
B. Only tasks 1 and 2 execute in arbitrary order.
C. Only tasks 1, 2, and 3 execute in arbitrary order.
D. Only tasks 1 through 9 execute in arbitrary order.
E. All tasks execute in arbitrary order.

Answer. As often happens with exam questions, the complexity of this code disguises the relative simplicity of the solution. Spotting the thing that really matters to solve the question quickly is really a manifestation of debugging skill. As such, it is not a trick question, but it can certainly be a little frustrating if you miss the key point. Never spend too long on one question until you’ve answered all the others—but we’ve made that point before.

This code uses the rangeClosed method of the IntStream class. This method produces a series of monotonically increasing int values starting with the first argument value and ending with the second argument value; that means 1 through 10 in this case. (If instead the range method had been used, the second argument would behave as a fence value; that is, the range produced would stop short of that second argument’s value.)

These 10 numbers are used to build tasks described by the Task class. The tasks all share a single CyclicBarrier, and each task is passed to the executor service for execution.

In the question, the code uses a thread pool that has two threads and a CyclicBarrier initialized with an argument value of 3.

The behavior of the CyclicBarrier may be thought of as a door with a handle. In this example, the door handle must be turned three times to open the door (that’s due to the argument of 3 in the constructor of the CyclicBarrier). The await method turns the door handle when it’s called. If a call is not the third call to await, the calling thread stops executing until other threads call await again, and at the third call the door opens. When the door opens, those three threads continue executing—they pass through the door, to continue this analogy—and the door closes behind them. Further threads calling await will again be made to wait, until another three calls to await have been made. This process continues; that’s why the CyclicBarrier is cyclic.

In this quiz’s code, there are exactly two threads in the pool. This means that only two tasks can be in process at any one instant. Note that tasks that are blocked in methods such as await are still in process. Therefore, the code has asked the pool to execute 10 tasks, but it gave the pool only two threads, so only two tasks can be in process at one time. As soon as the first two tasks have called await, their execution is on hold. The tasks are in process but waiting for the door to open. Because the pool only has two threads, no threads are available to execute a third task, and the door handle can never be turned for the crucial third time. The system simply stops right there, never to make any more progress. Also note that at this point, no output has been generated.

Next, consider the shutdown() method. This waits until all the in-process tasks are completed, but the two tasks that are waiting for that door to open will never continue executing, and they will never be complete. This also means that the other eight tasks never even start. Because of this, the program never ends, and no output is ever printed. This makes option A correct and options B, C, D, and E incorrect.

To understand how this works, imagine some variant scenarios.

Suppose you created three threads in the pool with Executors.newFixedThreadPool(3). In this situation, three tasks can be in process, and they will be able to call await the necessary three times. At that point, the first three tasks will move on and print the “Task executed” message. After those first three tasks are completed, the threads from the pool will become available and will pick up the next tasks, which are tasks 4, 5, and 6. These too will then be able to execute the await method three times, print their message, and finish. Then tasks 7, 8, and 9 will proceed to completion too. Unfortunately, the 10th task will be stuck, as there will not be the necessary additional two calls to await to allow it to be completed. Notice that in this scenario, the problem is that no task exists to make the call, not that there are no threads to run the tasks. But the bottom line is that task 10 would never print its message, and the program will still never terminate.

Another possible change would be to have two threads with Executors.newFixedThreadPool(2) and require two calls to await with new CyclicBarrier(2) instead of three calls. In this case, the tasks finish in groups of two because you need to turn the door handle only twice to open the door. Consequently, all 10 tasks would be completed, each printing its message. After all 10 have been completed, the program would shut down.

One final point: When three threads have called the await method, there’s no particular expectation that they will resume executing in the same order in which they arrived at the await method. Even if they did, the operating system’s thread scheduling could arbitrarily hold one up while letting another run freely, so that their relative arrival times at the printf statement would still not be predictable. Because of this, any output from the groups of two or three threads in the two alternative scenarios must be assumed to be printed in arbitrary order.

Conclusion. The correct answer is option A.

Source: oracle.com

Wednesday, January 18, 2023

Quiz yourself: Multithreading and the Java keyword synchronized

The goal is to obtain consistent results and avoid unwanted effects.


Imagine that you are working with multiple instances of the following SyncMe class, and the instances are used by multiple Java threads:

Quiz Yourself, Multithreading, Java Keyword Synchronized, Oralce Java Certification, Java Prep, Java Preparation, Java Tutorial and Materials

public class SyncMe {
    protected static synchronized void hi() {
        System.out.print("hi ");
        System.out.print("there! ");
    }
    public synchronized void bye() {
        System.out.print("bye ");
        System.out.print("there! ");
    }
    public synchronized void meet() {
        hi();
        bye();
    }
}

What statements are true about the class? Choose two.

A. Concurrent calls to the hi() methods can sometimes print hi hi.

B. Concurrent calls to the bye() methods can sometimes print bye bye.

C. Concurrent calls to the meet() method always print hi there! bye there!.

D. Concurrent calls to the meet() method can print bye bye.

E. Concurrent calls to the meet() method can print hi hi.

Answer. This question investigates the meaning and effect of the keyword synchronized and the possible behavior of code that uses it in a multithreaded environment.

One fundamental aspect of the keyword synchronized is that it behaves rather like a door.

◉ When a thread encounters such a door, it cannot execute past that point unless that thread carries, or can obtain, the right key to open the door.

◉ When the thread enters the region behind the door (the synchronized block), it keeps the key until it exits that region.

◉ When the thread exits the synchronized block, the thread is supposed to put the key back on the hook, meaning that another thread could potentially take the key and pass through the door.

Upon simple analysis, this behavior prevents any other thread from passing through that door into the synchronized block while the first thread is executing behind the door.

(This discussion won’t go into what happens if the key were already held by the thread at the point when it reached the door. Although that’s important to understand in the big scheme, it’s not necessary for this question because it does not happen in this example. Frankly, we’re also ignoring quite a bit of additional complexity that can arise in situations more complex than this question presents.)

In the real world, of course, it’s possible that several doors might require the same key or they might require different keys. The same is true in Java code, and for this question you must understand the different keys and the doors those keys open. Then you must think through how the code might behave when it’s run in a multithreaded environment.

The general form of the keyword synchronized is that it takes an object as a parameter, such as the following:

void doSyncStuff() {
  synchronized(this.rv) {
    // inside
  }
}

In this situation, the key required to open the door and enter the synchronized block is associated with the object referred to by the this.rv field. When a thread reaches the door, and assuming it doesn’t already have the key, it tries to take that key from the hook, which is that object. If the key is not on that hook, the thread waits until after the key is returned to that hook.

In the code for this question, it is crucial to realize that if there are two instances of the enclosing object and a different thread is executing on each of those instances, it’s likely there are two different keys: one for the door that’s encountered by one thread and another for the door encountered by the other thread. This is potentially confusing since it’s the same line of code, but the key required to open the door depends on the object referred to by this.rv.

Of course, the code for this question does not have a parameter after the keyword synchronized. Instead, synchronized is used as a modifier on the method. This is effectively a shortcut.

To explain, if the method is a static method, such as this

synchronized static void dSS() {
  // method body
}

and the enclosing class is MySyncClass, then the code is equivalent to this

static void dSS() {
  synchronized (MySyncClass.class) {
    // method body
  }
}

Notice that in this case, all the static synchronized methods in a single class will use the same key.

However, if the method is a synchronized instance method, like this

synchronized void dIS() {
  // method body
}

then it is equivalent to this

void dIS() {
  synchronized(this) {
    // method body
  }
}

It’s critical to notice that if you have two threads executing this same method on different object instances, different keys are needed to open the doors.

Given this discussion and noting that the hi() method is static but the other two are instance methods, and also that the question states that multiple objects exist, recognize that only one thread at a time can be executing the hi() method, but more than one thread might be executing the other two methods.

That tells you that whenever hi has been printed, another hi cannot be printed until after the printing of there!. You might see any of the output from invocations of the bye() method between hi and there!, but you’ll never see hi hi printed. From that you know that option A is incorrect.

Using the same logic as above, concurrent calls to meet() cannot result in hi hi being printed either, since that output is impossible no matter how the hi() method is invoked. That means that option E must also be incorrect.

By contrast, concurrent calls to the bye() method can execute concurrently if they are invoked on different instances of the class. In such a situation the output of the two invocations can become interleaved, and you might in fact see bye bye printed. That makes option B correct, and at the same time and for the same reason, it makes D correct, because concurrent calls to meet() can result in concurrent calls to the bye() method.

Option C must be incorrect, because it contradicts the notion that you can ever see bye bye printed.

Conclusion. The correct answers are options B and D.

Source: oracle.com

Wednesday, August 18, 2021

Multithreading in Java

Multithreading in Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms : 

1. Extending the Thread class 

2. Implementing the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.

// Java code for thread creation by extending

// the Thread class

class MultithreadingDemo extends Thread {

public void run()

{

try {

// Displaying the thread that is running

System.out.println(

"Thread " + Thread.currentThread().getId()

+ " is running");

}

catch (Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

}

}

}

// Main Class

public class Multithread {

public static void main(String[] args)

{

int n = 8; // Number of threads

for (int i = 0; i < n; i++) {

MultithreadingDemo object

= new MultithreadingDemo();

object.start();

}

}

}

Output

Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running

Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object. 

Multithreading in Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}

Output

Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running

Thread Class vs Runnable Interface 


1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.

2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.

3. Using runnable will give you an object that can be shared amongst multiple threads. 

Source: geeksforgeeks.org

Friday, August 6, 2021

Top 20 Java Multithreading Interview Questions & Answers

Java has been rated number one in TIOBE popular programming developers which are used by over 10 Million developers over 15 billion devices supporting Java. It is used for creating applications for trending technologies like Big Data to household devices like Mobiles and DTH Boxes, it is used everywhere in today’s information age.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Multithreading in Core Java(J2SE) is a very important topic from an interview point of view. It can lead you to become a Java Developer, Java Testing Engineer, Java Architect, Lead Analyst, Java Consultant, and most important a real good java programmer enabling the confidence to dive in J2EE programming that stands for Java to enterprising edition or in layman language making you fit to work in corporate domain workflow directly. Perks wide varied in India for Java developers from 300K to 25000K for as fresher based upon the level of intellect.

So, let’s get started with most asked Java Multithreading Interview Questions with their detailed answers.

Q-1 What is multitasking?

A multitasking operating system is an operating system that gives you the perception of 2 or more tasks/jobs/processes running at the same time. It does this by dividing system resources amongst these tasks/jobs/processes and switching between the tasks/jobs/processes while they are executing over and over again. Usually, the CPU processes only one task at a time but the switching is so fast that it looks like the CPU is executing multiple processes at a time. They can support either preemptive multitasking, where the OS provides time to applications (virtually all modern OS), or cooperative multitasking, where the OS waits for the program to give back control (Windows 3.x, Mac OS 9, and earlier), leading to hangs and crashes. Also known as Timesharing, multitasking is a logical extension of multiprogramming.

Multitasking programming is of two types which are as follows:

1. Process-based Multitasking
2. Thread-based Multitasking

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Note: Performing multiple tasks at one time is referred to as multithreading in java which is of two types namely Process-based multithreading and Thread based multithreading.

Q-2 How can you identify the process?

Any program which is in a working state is referred to as a process. These processes do have threads that are single dispatchable units.

Q-3 How do you see a thread?

In order to see threads status let us take windows as an operating system, it illustrates then we’d have ProcessExplorer where you can see GUI shown below for windows operating systems.

This PC > OS > Users > Oracle Java Certified > Downloads > ProcessExplorer

ProcessExplorer is illustrated below in the windows operating systems

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Note: All of them as listed in the above media are the processes as shown above where at a time many are running in parallel to each other henceforth illustrating multiprocessing in the Jwindows operating system.  

As we have seen threads do reside in a single process so we have to deep dive into a specific process to see them in order to show users how multithreading is going on in the computers at the backend. For example: let us pick a random process from the above media consisting of various processes say it be ‘chrome’. Now we need to right-click over the process and click the properties’ menu.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

From the above media, it is clearly perceived that chrome is a process and after proceeding with the steps to figure out threads running inside the chrome process we go to properties of the process ‘chrome’ below pictorial output will be generated representing threads running in the process chrome.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Note: If we look scroll way from up to down then it will be seeing some colors against a few of those threads. Here green color threads are associated as the newly created threads and red colors associated threads are representing the closed threads.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Note: So for chrome to increase the performance by reducing the response time that is referred to as Thread based multitasking.

Q-4 What is Multithreading and How it is Different from Multitasking?

Multithreading is a specialized form of multitasking. Process-based multitasking refers to executing several tasks simultaneously where each task is a separate independent process is Process-based multitasking. 

Example: Running Java IDE and running TextEdit at the same time. Process-based multitasking is represented by the below pictorial which is as follows:

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Thread-based multitasking refers to executing several tasks simultaneously where each task is a separate independent part of the same program known as a thread. For example, JUnits uses threads to run test cases in parallel. Henceforth, process-based multitasking is a bigger scenario handling process where threads handle the details. It is already discussed to deeper depth already with visual aids.

Q-5 Which Kind of Multitasking is Better and Why?

Thread-based multitasking is better as multitasking of threads requires less overhead as compared to process multitasking because processes are heavyweight in turn requiring their own separate address space in memory while threads being very light-weight processes and share the same address space as cooperatively shared by heavyweight processes.

Switching is a secondary reason as inter-process communication is expensive and limited. Context switching from one process to another is cost hefty whereas inter-thread communication is inexpensive and context switching from one thread to another is lower in cost. 

Note: However java programs make use of process-based multitasking environments, but this feature is not directly under Java’s direct control while multithreading is complete.

Q-6 What is a thread?

Threads are lightweight processes within processes as seen. In java, there are two ways of creating threads namely via Thread class and via Runnable interface.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Q-7 What are the different states of a thread, or what is thread lifecycle?

A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant:

1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Q-8 What is the task of the main thread?

All Java programs have at least one thread, known as the main thread which is created by JVM at the program start when the main() method is invoked with the main thread as depicted from the output perceived from pseudo-code illustration.

Illustration:

System.out.println(“Mayank Solanki”);
Output: Mayank Solanki

System.out.println(Thread.getname().currentthread()); 
Output: main

Q-9 What are Different Types of threads in Java? 

There are two types of threads in java as follows:

◉ User thread
◉ Daemon thread 

User threads are created by java developers for example Main thread. All threads are created inside the main() method are by default non-daemon thread because the ‘main’ thread is non-daemon. Daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection, etc. They do not prevent daemon threads from exiting when all user threads finish their execution. JVM terminates itself when all non-daemon threads finish their execution. JVM does not care whether a thread is running or not, if JVM finds a running daemon thread it terminates the thread and after that shutdown itself.

Q-10 How to Create a User thread?

As discussed earlier when the JVM starts it creates a main thread over which the program is run unless an additional thread is not created by the user. The first thing “Main” thread looks for ‘public static void main(String [] args)’ method to invoke it as it acts as an entry point to the program. All other threads created in main acts as child threads of the “Main” thread. 

User thread can be implemented in two ways listed below:

1. Using Thread class by extending java.lang.Thread class.
2. Using Runnable Interface by implementing it.

Q-11 How to set the name of the thread?

We can name a thread by using a method been already up there known as setName() replacing default naming which was ‘Thread-0’, ‘Thread-1’, and so on.

thread_class_object.setName("Name_thread_here");

Q-12 What is thread priority?

Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every object is having priority here which is represented by numbers ranging from 1 to 10. 

◉ The default priority is set to 5 as excepted.
◉ Minimum priority is set to 0.
◉ Maximum priority is set to 10.

Here 3 constants are defined in it namely as follows:

1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY

Q-13 How deadlock plays a important role in multithreading?

If we do incorporate threads in operating systems one can perceive that the process scheduling algorithms in operating systems are strongly deep-down working on the same concept incorporating thread in Gantt charts. A few of the most popular are listed below which wraps up all of them and are used practically in software development.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

◉ First In First Out
◉ Last In First Out
◉ Round Robin Scheduling

Now one Imagine the concept of Deadlock in operating systems with threads by now how the switching is getting computed over internally if one only has an overview of them. 

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Q-14 Why output is not ordered? 

Scheduling of threads involves two boundary scheduling,

◉ Scheduling of user-level threads (ULT) to kernel-level threads (KLT) via lightweight process (LWP) by the application developer.

◉ Scheduling of kernel-level threads by the system scheduler to perform different unique os functions.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

If multiple threads are waiting to execute then thread execution is decided by “ThreadScheduler” which is a part of JVM hence its vendor dependent resulting in unexpected execution of output order.

Note

◉ In multithreading, the guarantee of order is very less where we can predict possible outputs but not exactly one.
◉ Also, note that synchronization when incorporated with multithreading does affect our desired output simply by using the keyword ‘synchronized’.

It is as illustrated in the below illustration which is as follows:

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Q-15 What is Daemon Thread in Java and explain their properties? 

Daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection. It does possess certain specific properties as listed below:

◉ They can not prevent the JVM from exiting when all the user threads finish their execution.

◉ JVM terminates itself when all user threads finish their execution

◉ If JVM finds a running daemon thread, it terminates the thread and after that shutdown itself. JVM does not care whether the Daemon thread is running or not.

◉ It is an utmost low priority thread

Note: The main difference between user thread and daemon thread is that JVM does not wait for daemon thread  before exiting while it do waits for the user thread.

Q-16 How to Make User Thread to Daemon Thread?

It is carried out with the help of two methods listed in ‘Thread class’ known as setDaemon() and isDaemon(). First, the setDaemon() method converts user thread to daemon thread and vice-versa. This method can only be called before starting the thread using start() method else is called after starting the thread wit will throw IllegalThreadStateException After this, isDaemon() method is used which returns a boolean true if the thread is daemon else returns false if it is a non-daemon thread.  

Q-17 What are the tasks of the start() method?

The primary task of the start() method is to register the thread with the thread scheduler, so one can tell what child thread should perform, when, and how it will be scheduled that is handled by the thread scheduler. The secondary task is to call the corresponding run() method got the threads.

Q-18 What is the difference between the start() and run() method?

First, both methods are operated in general over the thread. So if we do use threadT1.start() then this method will look for the run() method to create a new thread. While in case of theadT1.run() method will be executed just likely the normal method by the “Main” thread without the creation of any new thread.

Note: If we do replace start() method with run() method then the entire program is carried by ‘main’ thread.

Q-19 Can we Overload run() method? What if we do not override the run() method? 

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Yes, it is possible to overload run() by passing parameters to it and also keeping a check over to comment down @override from the run() method. 

It should be as good as a thread wherein thread we do not have any arguments, so practice to overload is to comment on the call out for overloaded run() method. Now, so we need to acknowledge the same whether the output is the same or not if we have not overloaded it. 

If we have overloaded the run() method, then we will observe that output is always the main method as can be perceived from the stack call from the aboe image. It is because if we debug the code as provided in the link below we see as soon as the start() method is called again, run() is called because we have not overridden the run() method. 

The compiler will simply execute the run() method of the Thread class, keeping a check that the run() method of the Thread class must have an empty implementation. Hence, it results out in no output corresponding to the thread. As we have discussed above already, if we try to do so, then the Thread class run() method will be called and we will never get our desired output.

Note: Oracle Java Certified initially we are requesting to create a thread for us and later the same thread is doing nothing for us which we have created. So it becomes completely meaningless to us by writing unwanted operations to our code fragments. Hence, it becomes useless not to override the run() method. 

Q-20 Can we Override the start() method?

Even if we override the start() method in the custom class then no initializations will be carried on by the Thread class for us. The run() method is also not called and even a new thread is also not created.

Source: geeksforgeeks.org

Wednesday, June 3, 2020

Java - Multithreading

Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.

By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.

Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program.

Life Cycle of a Thread


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread.

Java - Multithreading, Oracle Java Guides, Oracle Java Learning, Oracle Java Tutorial and Material, Oracle Java Exam Prep

Following are the stages of the life cycle −

◉ New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

◉ Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

◉ Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

◉ Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

◉ Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities


Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.

Create a Thread by Implementing a Runnable Interface


If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps −

Step 1

As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method −

public void run( )

Step 2

As a second step, you will instantiate a Thread object using the following constructor −

Thread(Runnable threadObj, String threadName);

Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.

Step 3

Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −

void start();

Example

Here is an example that creates a new thread and starts running it −

Live Demo
class RunnableDemo implements Runnable {
   private Thread t;
   private String threadName;
 
   RunnableDemo( String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
 
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
      } catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
 
   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThread {

   public static void main(String args[]) {
      RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();
   
      RunnableDemo R2 = new RunnableDemo( "Thread-2");
      R2.start();
   } 
}

This will produce the following result −

Output

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Create a Thread by Extending a Thread Class


The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.

Step 1

You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method −

public void run( )

Step 2

Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −

void start( );

Example

Here is the preceding program rewritten to extend the Thread −

class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;
 
   ThreadDemo( String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
 
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
      } catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
 
   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThread {

   public static void main(String args[]) {
      ThreadDemo T1 = new ThreadDemo( "Thread-1");
      T1.start();
   
      ThreadDemo T2 = new ThreadDemo( "Thread-2");
      T2.start();
   } 
}

This will produce the following result −

Output

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Thread Methods


Following is the list of important methods available in the Thread class.

Sr.No.  Method & Description
1 public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.

The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread.

Sr.No.  Method & Description
1 public static void yield()
Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled.
public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number of milliseconds.
public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.
public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this method.
public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

Example

The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable −

// File Name : DisplayMessage.java
// Create a thread to implement Runnable

public class DisplayMessage implements Runnable {
   private String message;
   
   public DisplayMessage(String message) {
      this.message = message;
   }
   
   public void run() {
      while(true) {
         System.out.println(message);
      }
   }
}

Following is another class which extends the Thread class −

// File Name : GuessANumber.java
// Create a thread to extentd Thread

public class GuessANumber extends Thread {
   private int number;
   public GuessANumber(int number) {
      this.number = number;
   }
   
   public void run() {
      int counter = 0;
      int guess = 0;
      do {
         guess = (int) (Math.random() * 100 + 1);
         System.out.println(this.getName() + " guesses " + guess);
         counter++;
      } while(guess != number);
      System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**");
   }
}

Following is the main program, which makes use of the above-defined classes −

// File Name : ThreadClassDemo.java
public class ThreadClassDemo {

   public static void main(String [] args) {
      Runnable hello = new DisplayMessage("Hello");
      Thread thread1 = new Thread(hello);
      thread1.setDaemon(true);
      thread1.setName("hello");
      System.out.println("Starting hello thread...");
      thread1.start();
      
      Runnable bye = new DisplayMessage("Goodbye");
      Thread thread2 = new Thread(bye);
      thread2.setPriority(Thread.MIN_PRIORITY);
      thread2.setDaemon(true);
      System.out.println("Starting goodbye thread...");
      thread2.start();

      System.out.println("Starting thread3...");
      Thread thread3 = new GuessANumber(27);
      thread3.start();
      try {
         thread3.join();
      } catch (InterruptedException e) {
         System.out.println("Thread interrupted.");
      }
      System.out.println("Starting thread4...");
      Thread thread4 = new GuessANumber(75);
      
      thread4.start();
      System.out.println("main() is ending...");
   }
}

This will produce the following result. You can try this example again and again and you will get a different result every time.

Output

Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......

Wednesday, March 4, 2020

Thread, code and data - Story of a Multithreading Program in Java

Oracle Java Thread, Oracle Java Multithreading, Oracle Core Java, Oracle Java Prep

There are certain things, which you don't learn on academics or training class, you develop those understanding after few years of work experience, and then you realize, it was very basic, how come I had missed that all those years. Understanding of how a multi-threaded Java program executes is one of such things. You definitely have heard about threads, how to start a thread, how to stop a thread, definitions like its independent path of execution, all funky libraries to deal with inter-thread communication, yet when it comes to debugging a multithreaded Java program, you struggle.

At least I can say this from my personal experience. Debugging is in my opinion real trainer, you will learn a subtle concept and develop an understanding which will last long, only through debugging.

In this article, I am going to talk about three important things about any program execution, not just Java, Thread, code, and data.

Once you have a good understanding of how these three work together, it would be much easier for you to understand how a program is executing, why a certain bug comes only sometimes, why a particular bug comes all time and why a particular bug is truly random.

How Thread, Code, and Data work together


What is a program? In short, it's a piece of code, which is translated into binary instruction for  CPU. CPU is the one, who executes those instructions e.g. fetch data from memory, add data, subtract data etc. In short, what you write is your program, the Code.

What varies between the different execution of the same program, is data. It's not just mean restarting the program, but a cycle of processing, for example, for an electronic trading application, processing one order is one execution. You can process thousands of order in one minute and with each iteration, data varies.

One more thing to note is that you can create Threads in code, which will then run parallel and execute code, which is written inside their run() method. The key thing to remember is threads can run parallel.

When a Java program starts, one thread known as main thread is created, which executed code written inside the main method, if you create a thread, then those threads are created and started by the main thread, once started they start executing code written in their run() method.

Oracle Java Thread, Oracle Java Multithreading, Oracle Core Java, Oracle Java Prep

So if you have 10 threads for processing Orders, they will run in parallel. In short, Thread executes code, with data coming in. Now, we will see three different kinds of issue, we talked about

1) Issues, which always comes

2) Issues, which comes only sometimes, but consistent with the same input

3) Issues, which is truly random

Issue one is most likely due to faulty code, also known as programming errors e.g. accessing the invalid index of an array, accessing Object's method after making it null or even before initializing it. They are easy to fix, as you know their place.

 You just need to have knowledge of programming language and API to fix this error.

The second issue is more likely to do with data than code. Only sometimes, but always come with the same input, could be because of incorrect boundary handling, malformed data like Order without certain fields for example price, quantity etc.

Your program should always be written robustly so that it won't crash if incorrect data is given as input. The impact should only be with that order, the rest of the order must execute properly.

The third issue is more likely coming because of multithreading, where order and interleaving of multiple thread execution causing race conditions or deadlocks. They are random because they only appear if certain random things happen e.g. thread 2 getting CPU before thread 1, getting a lock on incorrect order.

Remember, Thread scheduler and Operating system are responsible for allocating CPU to threads, they can pause them, take CPU from them at any time, all these can create a unique scenario, which exposes multithreading and synchronization issue.

Your code never depends upon the order of thread etc, it must be robust to run perfectly in all condition.

In short, remember thread executes code with data given as input. Each thread work with the same code but different data. While debugging issue, pay attention to all three, Thread, Code and data.