Threads Flashcards

1
Q

Thread definition

A

Smallest unit of execution scheduled by Operating systems

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Process definition

A

A group of associated threads that execute in the same shared environment

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Multi-threaded process?

A

The process that has one or more threads

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Task?

A

Single unit of work performed by the thread

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the System Thread?

A

A system thread is created by JVM and runs in the background of application. Eg.. Garbage Collector

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Give some examples of problems that occur in System Thread? Whatexceptions do they throw?

A

Memory space Error.

They do not throw Exception, they throw Error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is User-defined threads?

A

A thread created by application developer to accomplish certain tasks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are daemon threads?

A

Threads that do not prevent JVM from exciting when the application finishes
Eg.., Garbage Collector. If GC is the only thread that is running, then JVM shuts down

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Concurrency?

A

The process of executing multiple threads at the same time is called as Concurrency

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does the operating systems uses to find which thread to execute?

A

Thread scheduler

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is context Switching?

A

It is the way of storing the current thread state and later reusing the state of the thread to continue execution

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

When is context switching be used?

A

When a thread doesnt complete its task in allotted time, context switch occurs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

what are the three constant thread Static constant variable that determines the Thread priority and their values?

A
  1. Thread.MIN_PRIORITY (1)
  2. Thread.NORM_PRIORITY (5)
  3. Thread.MAX_PRIORITY (10)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What happens when two or more threads have same priority?

A

The thread scheduler decides arbitrarily

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the Interface to implement to create a thread?

A

Runnable Interface. It is a functional Interface

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is special about Runnbale Interfaces?

A

It doesnt take any arguments and doesnt return anything

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the simplest way of creating a Thread?

A

Extending java.lang.Thread class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does Java does not guarantee?

A

It does not guarantee the order in which the thread will be processed once the thread starts

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What should we keep in mind on creating a thread using Runnable interface

A

We should pass the Runnable object to the Thread constructor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How should we start a thread?

A

We should call the ‘start()’ method that starts a new task for the Thread in operating systems

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Will the below compile? What is the actual implications?

new PrintData().run();
(new Thread(new PrintData())).run();
(new ReadInventoryThread()).run();
A

Yes, the below compiles. But the thread created each calls the run method and thus no seperate task on the OS is executed, causing each line to wait until the previous completes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Polling?

A

It is the process of intermittently checking the data at some fixed interval

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What method do we use generally for Polling?

A

Thread.sleep(long);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What exception does Thread.sleep method throws?

A

InterruptedException

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is ExecutorService?

A

In Concurrency APi, java introduces ExecutorService which creates and manages threads

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How ExecutorService works?

A

We get an instance of the ExecutorService interface and then send the service tasks to be processed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Executor Service is an interface. How do we get the ExecutorService instance?

A

Java concurrency API includes a Executors Factory class that can be used to get the instance

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is factory Pattern?

A

It is the creational pattern where the underlying implementation details of object creation is hidden from us.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is the package of ExecutorService?

A

Java.util.concurrent

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Method to use to get the simple ExecutorService?

A

newSingleThreadExecutor() method in Executors class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What should we keep in mind for Single-thread executor regarding order of execution?

A

Results are guaranteed to be executed in the order in which they are added. But we should not rely on this

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is the importance of calling Executors shutDown() method?

A

The thread executor creates a non-deamon thread on first task, so failing to call shutdown results in application never terminating

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

what are the process involved in shutDown method?

A
  1. rejecting any new task submitted to thread executor

2. continuing with the previously submitted task.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What does calling isShutDown and isTerminated method returns while shutDown is called?

A

isShutDown() returns true

isTerminated() returns false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What will happen if we try to submit a new task to thread executor when it is shutting down?

A

‘RejectedExecutionExecption’ exception is thrown

36
Q

Will shutDown() actually stop any tasks that have already been submitted to thread executor?

A

No. We have to invoke shutDownNow() which attemps to stop all running tasks and discards any that have not been started

37
Q

What does shutDownNow() returns?

A

It returns List of tasks that are submitted to Thread executor but never started

38
Q

Can we use try-with-resources with ExecutorService?

A

No, ExecuterService did not implement AutoClosable interface.

39
Q

What is submit() and why it is being used?

A
It is same as execute() method that completes task asynchronously.
But Execute() doesnt return anything. submit() returns a FUTURE object that is used to determine the state of thread in future
40
Q

What does invokeAny() and invokeAll() method takes as aarguments? They are synchronous or asynchronous?

A

The collection of tasks to be executed. They are Synchronous

41
Q

invokeAll() method?

A
  1. InvokeAll method executes all tasks in the collection passed
  2. Resturns a list of Ordered Future Objects
  3. One Future object corresponds to the One completed tasks in the order passed.
  4. Futures.isDone9) returns true even though a task have completed normally or exception is thrown
42
Q

invokeAny()

A
  1. This executes a collection of tasks and return the result of one successfully completed task.
  2. cancels all unfinished work
    3.
43
Q

difference b/w invoke and invokeAll()

A
  1. InvokeAll() method wait indefinitely for all tasks are complete. InvokeAny() method waits indefinitely for atleast one task completes.
  2. invokeAll and invokeAny are overlaoded to take TmeOut value and TimeOutUnit parameter.
44
Q

How do we know that the task submitted to submit() is completed or not?

A

The submit() method returns a java.util.concurrent.Future object, that can be used to return the result

45
Q

Write a submit method for determinging whether a String is printed n console.

A

Future> future = service.submit(() -> Syso(“Hello”));

46
Q

What is Callable interface

A
  1. It is a functional interface with call() method.

2. call() method returns a value and throws checked Exceptions

47
Q

Definition of Callable interface

A
@FunctionalInterface
public interface Callable{
   V call() throws Exception;
}
48
Q

What is the difference between Supplier and Callable?

A

Both takes anon argument but return a value.

One difference is Callable throws checked Exception

49
Q

public static void use(Callable expression){}
public static void use(Supplier expression){}

use(() -> {throw new IOException();});

What is the issue here and how to overcome it?

A

use method is overloaded with Callable and Supplier interface. So, java doesnt understand which use it is being called. So we get compiler error.

Now we have to cast it to resolve this issue.

use((Callable)() -> {throw new IOException();});

50
Q

What will we get on calling Futures’s get() on Runnable

A

Runnable doesnt return anything. So we always get null;

51
Q

Suppose assume that we have a ExecutorService instance ‘service’.

service. submit(() -> {Thread.sleep(1000); return null;});
service. submit(() -> {Thread.sleep(1000);});

which compiles and which doesnt?

A
  1. Compiles. because Thread.sleep throws checked Exception ‘Interrupted Exception’. So the first mabda expression returns null, the compiler treats this as a callable interface(callable interface throws exception)
  2. Doesnt compile, the method doesnt return anything, thus it is considered as Runnable. Since Runnable doesnt support checked Exceptions, thecompiler will report an error
52
Q

What are the two options to await repose for our tasks

A
  1. call the each Future’s object get method returned by submitmethod.
  2. call the executors shut down method. Then call awaitTermination(some timeout paramaters). the method waits for specified time for executors to stop.returnind sooner if all task completed or throws interrupted exception
53
Q

What is the interface we use for Scheduling tasks

A

ScheduledExecutorService interface. It is the sub interface of ExecutorService.

54
Q

How to get the instance of ScheduledExecutorService

A

ScheduledExecutorService service = Executors.newSingleThreadSchedulerExecutor();

55
Q

Very important 4 methods of scheduling a task.

A

Please refer346

56
Q

scheduleAtFixedRate()

A

It creates a task and submits to the excutor in specifid period, regardless of whether or not the previous task completed

57
Q

ScheduleAtFixedDelay()

A

creates a new Task after previous task has finished

58
Q

Why it is not a good idea to shutdown an executor service in finally block?

A

Sometimes we may need to create a static reference for executor service that can be shared by many codes.
In those cases, we need to create static method to be called anytime whenever we need to shotdown executor.

There is a possibility that we dont shutdown properly and thus the thread doesn’t stops and program hangs

59
Q

What is a thread pool?

A

A group of pre-instantiated reusable threads that are available to perform a set of arbitrary tasks

60
Q

What are the three other factory methods in Executor class that acts on thread pool and their return types.

A
  1. newCachedThreadPool (ExecutorService)
  2. newFixedThreadPool(int nThreads) (ExecutorService)
  3. newScheduledThreadPool(int nThreads) (ScheduledExecutorService)
61
Q

What is the difference b/w Single and Pooled Thread executors?

A
  1. Single-threaded executor wait for an available thread to become available for running next task
  2. Pooled-thread executor can execute the next task concurrently
62
Q

What happens when the pools run out of available threads?

A

The tasks will be queued by Thread executors and wait to be completed

63
Q

Some key points on newCachedThreadPool

A
  1. This method creates a thread pool of unbounded size.
  2. Allocates a new thread whenever one is required or all existing threads are busy
  3. Most commonly used for short-lived asynchronous threads
64
Q

Some key points on newFixedThreadPool()

A
  1. Takes a number of threads and allocates them all upon creation.
  2. As long as no of tasks is less than the no of threads, all tasks will be excuted concurrently
  3. If no of tasks exceeded the available noof threads, then they will wait in similar manner to single-threaded executor
65
Q

calling a newFixedThreadPool() with the value of 1 equivalent to?

A

calling a newSingleThreadExecutor()

66
Q

some key points on newScheduledThreadPool()

A

it is identical to newFixedThreadPool, except that it returns the instance of ScheduledExecutorService

67
Q

How does it differs from scheduleAtFixedRate() performs?

A

If the pool size is sufficiently large, say 10, then as each thread finishes, it is returned to the pool and results in a new threads available for next tasks

68
Q

determining the No of CPUs available

A

Runtime.getRuntime().availableProcessors()

69
Q

Which type of values does the atomic packages helps to coordinate with?

A

primitive values and Object references

70
Q

Which operator is not thread safe?

A

increment operator (++)

71
Q

What is atomic?

A

Atomic is the property of an operation to be carried out as a single unit of execution without any interference of other threads

72
Q

What happens in an atomic operation?

A

Any thread has to wait if an atomic operation is in progress.
It can access only after atomic operations are completed

73
Q

What are different atomic classes?

A
  1. AtomicBoolean
  2. AtomicInteger
  3. AtomicIntegerArray
  4. AtomicLong
  5. AtomicLongArray
  6. AtomicReference
  7. AtomicReferenceArray
74
Q

What is AtomicReference?

A

A generic object reference that may be updated atomically

75
Q

AtomicReferenceArray

A

An array of generic object references in which elements may be updated atomically

76
Q

What does get(), set() and getAndSet() means?

A

get() -> retrieves the current value
set() -> set the given value, equivalent to = operator
getAndSet() -> Atomically sets the value and return the old value

77
Q

incrementAndGet(), getAndIncrement(), decrementAndGet(), getAndDecrement()

A

As name suggest, for numeric classes
incrementAndGet() -> Atomic preincrement operation, equivalent to ++value
getAndIncrement() -> For numericvalues, atomic post-icrement operation equivalent to value++

decrementAndGet() -> –value
getAndDecrement() -> value–

78
Q

What is mean by acquiring a lock?

A
  1. Each thread arrives will first check if any threadsare in the block
  2. If not, it acquires the lock for that block and enter the block and preventing other threads from entering the block.
  3. All other threads wait for the first thread to finish
  4. Once the thread finishes executing the block, it will release the lock, allowing another one to proceed
79
Q

What should we make sure while synchronizing?

A
  1. We should make sure to synchronize not only the creation of threads but also the execution of the task
80
Q

Which method do we prefer for Executors? and why?

A

We prefer submit() over execute() because submit returns FUTURE object and supports Callable interface which execute doesnt supports

81
Q

How does invoke and invokeall methods work? synchronous or asynchronous?

A

asynchronous

82
Q

Which object is used as a monitor when we synchronize on a static method?

A

Class object!

83
Q

When do we need to use static synchronization?

A

If we need to order synchronization across all instances rather than a single instance

84
Q

wHAT happens when two or more threads try to modify a same collection?

A

ConcurrentModificationException

85
Q

What is the only difference between ScheduledFuture

and Future Object

A

Both are identical, except that ScheduledFuture includes a getDelay() method that returns the delay set when the process was created