Sunday, January 17, 2021

Interfaces in Java - questions and answers

What is an interface in Java and why would you, as a software developer, use interfaces?

An Interface in Java programming is defined as an abstract type used to specify the behavior of a class. A Java interface contains static constants and abstract methods. A class can implement multiple interfaces. In Java, interfaces are declared using the interface keyword.

What is an interface in Java?

Interface looks like a class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static & final by default. 

What is the use of interface in Java?

As mentioned above they are used for full abstraction. Since methods in interfaces do not have a body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, java programming language does not allow you to extend more than one class, However you can implement more than one interface in your class.

What is the difference between an abstract class and an interface?

The key technical differences between an abstract class and an interface are: Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs.

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. 


Why is abstraction an important concept in software development
and what role do interfaces play in abstraction?

Abstraction is one of the key elements of good software design. It helps encapsulate behavior. It helps decouple software elements. When developing with higher level of abstraction, you communicate the behavior and less the implementation.

Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it. Using interfaces, you can achieve (complete) abstraction.

What must a class do in order to implement an interface?

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

What is an abstract method?

Abstract Class is a type of class in OOPs, that declare one or more abstract methods. These classes can have abstract methods as well as concrete methods. A normal class cannot have abstract methods. An abstract class is a class that contains at least one abstract method as defined below:

Abstract Method is a method that has just the method definition but does not contain implementation. A method without a body is known as an Abstract Method. It must be declared in an abstract class. The abstract method will never be final because the abstract class must implement all the abstract methods.

The main benefit of using an Abstraction in Programming is that it allows you to group several related classes as siblings. Abstraction in Object Oriented Programming helps to reduce the complexity of the design and implementation process of software.

Abstract methods are mostly declared where two or more subclasses are also doing the same thing in different ways through different implementations. It also extends the same Abstract class and offers different implementations of the abstract methods.

Can you instantiate an interface?

An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface. A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.

Can you declare a constructor inside an interface? If not, why?

No, you cannot have a constructor within an interface in Java. You can have only public, static, final variables and, public, abstract, methods as of Java7. From Java8 onwards interfaces allow default methods and static methods.

Can we override an interface method with visibility that is not public?

If the method signature you defined in interface has public access specifier then you have to override that method, with the same method signature (that means with public access specifier) whenever you implement the interface to any class.

Thursday, January 14, 2021

Basic answers to complicated concepts in Java

What are deadlock, livelock, and starvation? What causes these conditions?


Deadlock describes a situation where two more threads are blocked because of waiting for each other forever. When deadlock occurs, the program hangs forever and the only thing you can do is to kill the program.

Livelock describes situation where two threads are busy responding to actions of each other. They keep repeating a particular code so the program is unable to make further progress:

  • Thread 1 acts as a response to action of thread 2
  • Thread 2 acts as a response to action of thread 1

Unlike deadlock, threads are not blocked when livelock occurs. They are simply too busy responding to each other to resume work. In other words, the program runs into an infinite loop and cannot proceed further.

Starvation describes a situation where a greedy thread holds a resource for a long time so other threads are blocked forever. The blocked threads are waiting to acquire the resource but they never get a chance. 

Thus they starve to death.

Starvation can occur due to the following reasons:
  • Threads are blocked infinitely because a thread takes long time to execute some synchronized code (e.g. heavy I/O operations or infinite loop).
  • A thread doesn’t get CPU’s time for execution because it has low priority as compared to other threads which have higher priority.
  • Threads are waiting on a resource forever but they remain waiting forever because other threads are constantly notified instead of the hungry ones.
When a starvation situation occurs, the program is still running but doesn’t run to completion because some threads are not executed.

What happens if you don’t override the thread class run() method?

  • In Thread class, run() method is defined with an empty implementation.
  • If we override run() method in the user-defined thread then in run() method we will define a job and Our created thread is responsible to execute run() method.
  • It is highly recommended to override run() method because it improves the performance of the system.
  • If we don't override Thread class run() method in our defined thread then Thread class run() method will be executed and we will not get any output because Thread class run() is with an empty implementation.

What is atomic operation and what are atomic classes in the Java Concurrency API?


An atomic operation is an operation which is performed as a single unit of work without the possibility of interference from other operations. The Java language specification guarantees that reading or writing a variable is an atomic operation (unless the variable is of type long or double).

The most commonly used atomic variable classes in Java are AtomicInteger, AtomicLong, AtomicBoolean, and AtomicReference. These classes represent an int, long, boolean, and object reference respectively which can be atomically updated.

What are Executor and ExecutorService and what are the differences between them?


The main difference between Executor, ExecutorService, and Executors class is that Executor is the core interface which is an abstraction for parallel execution. ... It also provides a submit() method which extends Executor. execute() method and returns a Future.



What are Concurrent Collection Classes?


Concurrent collections in java are designed and optimized specifically for synchronized multithreaded access. These are the thread safe collections, and these are existing in java.util.concurrent package.

Some Java Concurrent collection classes are:
  • Immutable List - read-only. You can’t modify the content of the immutable List after declaration. So an immutable list is threaded safe.
  • CopyOnWriteArrayList - is a thread-safe version of ArrayList. Multiple threads can read the data but only one thread can write the data at one time.
  • Immutable Set - can have a collection of objects like HashSet but we can’t modify the objects of the immutable set. If we try to add or remove any object in immutable set it throws UnsupportedOperationException.
  • CopyOnWriteArraySet - extends the AbstractSet class and implements the Serializable interface: well suited if you have small size collection and want to perform only read operation by multiple threads.
  • ConcurrentHashMap - is the concurrent version of the HashMap. It internally maintains a HashTable that is divided into segments. The number of segments depends upon the level of concurrency required the Concurrent HashMap. By default, it divides into 16 segments and each Segment behaves independently. It doesn’t lock the whole HashMap as done in HashTables/SynchronizedMaps, it only locks the particular segment of HashMap.

What is Java Memory Model (JMM)?

The Java memory model (JMM) describes how threads in the Java 
programming language interact through memory.

The Java memory model was the first attempt to provide a comprehensive memory model for a popular programming language and was justified by the increasing prevalence of concurrent and parallel systems, and the need to provide tools and technologies with clear semantics for such systems. 

The above sounds very complicated so let's break it down into layman's terms!

From my previous posts I think we can agree that computers and what they do can be understood on a very basic level - however, the complexity which results from the processor being able to do many things at once (at least, it appears that way to us humans) means that we have to manage that complexity.

Producing a feasible model allows us to interact with the concepts and processes that are part of any programming language. Also, giving stuff acronyms makes you look very clever! 

On modern platforms, code is frequently not executed in the order it was written - this does not make sense to our logical brains because we tend to want a direct line of thought, i.e start, continue then end.

Before your game loads stuff happens in the background - a bit like looking at the end of a non-fiction book and using the index listing to see where the interesting things are, your program first gets compiled. Now here's where it's interesting: we would put a book together with the intro page first, the chapters in sequential order and then at the end have the reference section.

A computer doesn't see life this way! It goes and looks for the juicy bits first before reading the novel and remembers where they were and what they do. Then it reads through volumes of only moderately interesting pages and doesn't care about what order they are in! This is called compiling which comes from the Latin verb compīlō, meaning "heap" or "plunder".

This way, maximum performance can be achieved - the JMM defines the allowable behavior of multithreaded programs by placing constraints on the way the threads and the memory interact with each other.

There are voluminous reference works available on this subject, all very in-depth and not needed here where I am giving an overview of this concept. For further reading, please browse Wikipedia and where you find some new insight, dive right in and explore!

Now let's pay cat tax - here is a word salad of some of the interesting terms associated with JMM:)



How do you create a daemon thread?

Creating a thread as a daemon in Java is as simple as calling the setDaemon() method. 

A setting of true means the thread is a daemon; false means it is not. By default, all threads are created with an initial value of false.

Java Daemon Thread Example

  1. You can make any java thread as daemon thread. Daemon threads acts like service providers for other threads running in the same process.

  2. Daemon threads will be terminated by the JVM when there are none of the other threads running, it includes main thread of execution as well.

  3. To specify that a thread is a daemon thread, call the setDaemon() method with the argument true.

  4. To determine if a thread is a daemon thread, use the accessor method isDaemon().

Have a go - run the script above and you will be able to answer this question :)

What is a daemon thread and what are its use cases?

A daemon thread is a background service thread which runs as a low priority thread
and performs background operations like garbage collection.

So that we understand a little more about this let us compare daemons with users in the context of talking about threads:

Firstly, daemon threads are low priority threads which always run in background;  and user threads are high priority threads which always run in foreground. 

Secondly, user threads (also referred to as non-daemon) are designed to do specific or complex tasks whereas daemon threads are used to perform supporting tasks.

As long as we can keep in mind that the JVM exits if only daemon threads are remaining it makes sense in terms of their hierarchy.




What are the different states of a thread and when do the state transitions occur?

Here we examine the life cycle of a thread and how it transitions into the next state:
A simplified approach

Like most things, threads have a cycle of being born and eventually dying! As yet, we don't know whether they achieve supreme consciousness or re-incarnate ... that is a topic for philosophers:)

We can draw some similarities to humans in that they are born (new), learn to crawl (runnable but not running), walking, then running. In our lives we learn and interact based on experience and the information we are given. We experience blockages or periods where we have to wait for the next event to happen and along the road we sometimes pause and relinquish control to another person or group.

At the end of it all we die or terminate - sad, but true that when the work is done then it's all over! We stop being consumers and for a thread this applies to using the CPU.

Let's summarize in the table below for quick reference:




Wednesday, January 13, 2021

How do you create a thread in Java and run it?

The answer lies in the commands we will use, which are:
Thread.start() and Thread.run() in Java

Reading this with no programming knowledge, it makes sense to say that creating is the start of the exercise and that after it is created/started it will be run. 

These are the most important things to remember when you are multi-threading (or as I like to call it multi-tasking): it's where you are already busy in for example the kitchen (i.e. you are already cooking or running a thread) in my previous post; and you can get the next item ready while you are still stirring away or setting a timer, i.e. filling the kettle with cold water is the step before you can create boiling water and starting it would be when you turn the kettle on. 

Will the kettle stop while you are still stirring your sauce? If you are reliant on Eskom it is anybody's guess but it will mostly stop automatically once temperature is reached.

I love making tables to visually and linguistically demonstrate what we are talking about and it follows below:



What is the difference between process and thread?

A process means that a program is in execution, whereas thread refers to a segment of a process. 

Processes are seen as being not lightweight where threads are considered lightweight - in basic English let's just call them heavy (process) and light (thread)! 

Threads share memory and data with other threads, compared to a process which is mostly isolated. Threads are a bit like social media influencers, always sharing away whenever they can and in the same light-hearted analogy, a process is that 28 year old video gamer living in mum's basement, not communicating very much at all:) 

When we look at a program while it is executing we could see it as being the major activity on your computer - like driving a car where you are fully engaged in operating the mechanisms of the vehicle to accelerate, stop or change gears. In this context a thread is the bit where you are also engaged in checking your mirror, steering and on a straight road operating the radio. 

This brings us to the question of when you use which procedure?

Let's simplify this and think of when we can only perform one action at a time, compared to when we can multi-task. Cooking a meal offers a good example - when you are making a sauce that demands all your attention you can't be side-tracked! However, nothing is preventing you from having a kettle boiling, ready for use; turning on the oven for the next stage of your dish and occasionally stirring another pot on the stove. 

This table below lays out the differences for easy reference: