YouTube Icon

Interview Questions.

Top 41 C# Developer Multi Threading Interview Questions - Jul 25, 2022

fluid

Top 41 C# Developer Multi Threading Interview Questions

Q1. What Is The Meaning Of Deadlocks?

A impasse takes place while two threads each watch for a aid held by way of the opposite, so neither can continue. The simplest  manner to demonstrate that is with  locks:

item locker1 = new object();

object locker2 = new item();

new Thread (() => 

lock (locker1)

Thread.Sleep (1000);

lock (locker2); // Deadlock

).Start();

lock (locker2)

Thread.Sleep (one thousand);

lock (locker1); // Deadlock

More elaborate deadlocking chains can be created with three or more threads.

Deadlocking is one of the toughest issues in multithreading—especially when there are numerous interrelated objects. Fundamentally, the difficult hassle is which you cannot make certain what locks your caller has taken out.

So, you might innocently lock personal discipline a within your class x, unaware that your caller (or caller's caller) has already locked discipline b inside class y. Meanwhile, any other thread is doing the reverse—growing a impasse. Ironically, the hassle is exacerbated via (proper) object-orientated design styles, due to the fact such patterns create name chains that are not determined until runtime. The popular recommendation, “lock gadgets in a steady order to avoid deadlocks,” although useful in our preliminary instance, is hard to use to the situation just described. A higher method is to be wary of locking round calling methods in objects

that could have references returned in your very own item. Also, don't forget whether or not you really want to lock round calling strategies in other classes (regularly you do—as we’ll see later—but every now and then there are different options). Relying greater on declarative and data parallelism, immutable types, and nonblocking synchronization constructs, can reduce the want for locking.

Q2. How Will You Take Thread Dump In Java? How Will You Analyze Thread Dump?

A Thread Dump is a entire list of lively threads. A java thread sell off is a way of locating out what every thread within the JVM is doing at a selected factor of time. This is specifically useful while your java utility appears to have a few overall performance issues. Thread unload will help you to find out which thread is inflicting this. There are numerous methods to take thread dumps from a JVM. It is tremendously endorsed to take extra than 1 thread dump and examine the results primarily based on it. Follow below steps to take thread sell off of a java manner 

Step 1 

On UNIX, Linux and Mac OSX Environment run under command: 

ps -el task supervisor and locate the PID of the java process 

Step 2: 

Use jstack command to print the Java stack strains for a given Java technique PID 

jstack [PID] 

Q3. What Is The Naming Threads ?

Each thread has a Name belongings that you may set for the advantage of debugging.This is in particular beneficial in Visual Studio, for the reason that thread’s call is displayed in the Threads Window and Debug Location toolbar. You can set a thread’s name simply once; tries to alternate it later will throw an exception. The static Thread.CurrentThread property gives you the currently executing thread. In the subsequent example, we set the principle thread’s call:

magnificence ThreadNaming

static void Main()

Thread.CurrentThread.Name = "primary";

Thread worker = new Thread (Go);

worker.Name = "employee";

worker.Start();

Go();

static void Go()

Console.WriteLine ("Hello from " + Thread.CurrentThread.Name);

Q4. What Is A Deadlock?

Deadlock is a state of affairs in which  or extra threads are blocked forever, expecting every different. This may additionally arise whilst two threads, each having a lock on one useful resource, attempt to gather a lock on the other's useful resource. Each thread would wait indefinitely for the other to launch the lock, except one of the user techniques is terminated. In terms of Java API, thread impasse can arise in following situations: 

When  threads call Thread.Be a part of() on every other.

When  threads use nested synchronized blocks to lock two objects and the blocks lock the same items in exclusive order.

Q5. What Is The Difference Between Threads Vs Processes ?

A thread is analogous to the operating machine technique in which your utility runs. Just as techniques run in parallel on a computer,threads run in parallel within a single process. Processes are absolutely remoted from every other; threads have only a restricted diploma of isolation. In specific, threads percentage (heap) memory with other threads going for walks within the identical application. This, in component, is why threading is useful: one thread can fetch records within the heritage, as an example, at the same time as every other thread can display the data as it arrives.

Q6. What Is Thread ?

A thread is essentially a separate collection of guidance designed to appearing a " unique venture" within the application.

Q7. Can We Synchronize The Run Method? If Yes Then What Will Be The Behavior?

Yes, the run method of a runnable elegance can be synchronized. If you're making run approach synchronized then the lock on runnable object can be occupied before executing the run method. In case we begin more than one threads the usage of the identical runnable item inside the constructor of the Thread then it might work. But till the 1st thread ends the 2nd thread can not begin and till the 2d thread ends the next can't start as all the threads depend upon lock on equal item

Q8. What Are The Methods Used In Thread Class?

Join

Resume

sleep

Spin Wait

Suspended

Start

Interrupt

Q9. What Are The Two Types Of Thread In C# ?

Foreground thread

Background thread

Q10. What Is Multithreading In C# ?

Performing more than one challenge at identical time during the execution of a software,is referred to as multithreading.

Q11. What Are The Methods Used In Monitor Class?

Enter

Exit

TryEnter

Wait

GetType

Q12. What Is The Use Of Thread Class In C#?

The Thread magnificence is used to perform responsibilities such as growing and putting the priority of a thread.

Q13. What Are The Syntax For Creating And Starting A Thread In C#?

First outline a delegate:-

Public delegate void start_thread();

Create a brand new thread:-

Thread thread_name = new Thread(new start_thread(method_name));

Q14. What Is The Thread Pool Class In C#?

The Thread Pool class is used,to carry out task inclusive of processing of asynchronous i/o and waiting on behalf of some other thread.

Q15. What Is Monitor Class In C# ?

The Monitor magnificence is used to get admission to an object via granting a lock for the item to a unmarried thread.

Q16. Why Do We Need Run() & Start() Method Both. Can We Achieve It With Only Run Method?

We want run() & begin() method each due to the fact JVM needs to create a separate thread which can't be differentiated from a everyday approach call. So this activity is executed with the aid of start method native implementation which must be explicitly called. Another benefit of having these  techniques is we are able to have any item run as a thread if it implements Runnable interface. This is to avoid Java more than one inheritance troubles with the intention to make it difficult to inherit any other class with Thread. 

Q17. What Is The Difference Between Monitor.Input And Monitor.Go out?

C#’s lock declaration is in reality a syntactic shortcut for a name to the techniques Monitor.Enter and Monitor.Exit, with a attempt/sooner or later block. Here’s (a simplified version of) what’s truely taking place inside the Go technique of the preceding   

instance:

Monitor.Enter (_locker);

try

if (_val2 != 0) Console.WriteLine (_val1 / _val2);

_val2 = 0;

in the end  Monitor.Exit (_locker); 

Calling Monitor.Exit with out first calling Monitor.Enter on the same object throws an exception.

Q18. What Are The Main Properties Of Thread Class?

Priority Thread State IsAlive Current thread Name and so forth.

Q19. What Are The Priority Value Used For Scheduling A Thread In C# ?

Highest

Normal

AboveNormal

BelowNormal

Lowest

Q20. What Is Mutex Class In C#?

A Mutex is used ,to carry out interprocess synchronization and a thread to have exceptional access to shared resources.

Q21. What Is The Namespace Used For Multithreading In C# ?

The usage of System.Threading;

Q22. What Is Immutable Object? How Does It Help In Writing Concurrent Application?

An object is taken into consideration immutable if its nation cannot trade after it's far built. Maximum reliance on immutable items is broadly frequent as a valid method for growing simple, dependable code. Immutable gadgets are especially beneficial in concurrent applications. Since they can't trade kingdom, they cannot be corrupted by using thread interference or discovered in an inconsistent kingdom. Examples of immutable objects from the JDK consist of String and Integer. Immutable gadgets greatly simplify your multi threaded application, due to the fact that they're 

Simple to construct, take a look at, and use.

Automatically thread-secure and haven't any synchronization issues.

To create a object immutable You want to make the magnificence very last and all its member very last so that after gadgets gets crated nobody can alter its state. You can achieve identical functionality by making member as non final but personal and not enhancing them besides in constructor. 

Q23. What Is The Difference Between Join And Sleep ?

You can look forward to any other thread to stop through calling its Join approach. For example:

static void Main()

Thread t = new Thread (Go);

t.Start();

t.Join();

Console.WriteLine ("Thread t has ended!");

static void Go()

for (int i = zero; i < one thousand; i++) Console.Write ("y");

This prints “y” 1,000 times, followed by “Thread t has ended!” at once afterward. You can include a timeout whilst calling Join, both in milliseconds or as a TimeSpan. It then returns actual if the thread ended or false if it timed out.

Q24. What Are The Methods Used In Mutex Class ?

Equals

close

OpenExisting

SetAccessControl

Release Mutex

Q25. What Is Thread Pool? Why Should We Use Thread Pools?

A thread pool is a group of threads on which challenge may be scheduled. Instead of creating a new thread for every undertaking, you may have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is completed with the task, it adds itself lower back to the pool and waits for another assignment. One common type of thread pool is the fixed thread pool. This type of pool usually has a specific number of threads running; if a thread is come what may terminated whilst it's miles nonetheless in use, it is automatically changed with a new thread. Below are key motives to use a Thread Pool 

Using thread pools minimizes the JVM overhead due to thread introduction. Thread gadgets use a substantial amount of memory, and in a big-scale application, allocating and de-allocating many thread objects creates a significant memory management overhead.

You have manipulate over the most number of responsibilities which might be being processed in parallel (= range of threads inside the pool).

Most of the executor implementations in java.Util.Concurrent use thread swimming pools, which encompass employee threads. This form of thread exists one by one from the Runnable and Callable obligations it executes and is regularly used to execute more than one obligations. 

Q26. What Are The Method Used In Thread Pool Class ?

Gettype

Equals

SetMaxThreads

QueueUserWorkItem

Q27. How Can I Trace Whether The Application Has A Thread Leak?

If an utility has thread leak then with time it'll have too many unused threads. Try to discover what sort of threads is leaking out.

This can be executed the usage of following methods 

Give unique and descriptive names to the threads created in utility. - Add log entry in all thread at various entry and exit points in threads.

Change debugging config levels (debug, data, error etc) and examine log messages.

When you discover the magnificence that is leaking out threads check how new threads are instantiated and how they are closed.

Make certain the thread is Guaranteed to shut well through doing following - Handling all Exceptions well.

Make certain the thread is Guaranteed to close nicely by using doing following

Handling all Exceptions nicely.

Liberating all resources (e.G. Connections, files and so on) before it closes.

Q28. What Are The Classes Used In System.Threading Namespace ?

Thread Thread Pool Monitor Mutex

Q29. When Invalidmonitorstateexception Is Thrown? Why?

This exception is thrown when you strive to call wait()/notify()/notifyAll() any of these methods for an Object from a point for your software in which u are NOT having a lock on that object.(i.E. U r now not executing any synchronized block/technique of that object and nonetheless trying to call wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. Considering This exception is a subclass of RuntimeException so we r no longer sure to seize it (despite the fact that u might also if u want to). And being a RuntimeException this exception is not noted in the signature of wait(), notify(), notifyAll() techniques. 

Q30. What Is The Meaning Semaphore ?

A semaphore is sort of a nightclub: it has a certain capability, enforced through a bouncer. Once it’s full, no extra human beings can input, and a queue builds up outdoor. Then, for anyone that leaves, one person enters from the head of the queue. The constructor calls for a minimum of two arguments: the wide variety of locations currently to be had within the nightclub and the membership’s overall ability.

A semaphore with a capacity of one is just like a Mutex or lock, besides that the semaphore has no “proprietor”—it’s thread-agnostic. Any thread can name Release on a Semaphore, while with Mutex and lock, only the thread that received the lock can launch it. 

Semaphores may be beneficial in proscribing concurrency—stopping too many threads from executing a selected piece of code at once. In the subsequent example, 5 threads attempt to input a nightclub that allows best three threads in without delay:

magnificence TheClub // No door lists!

Static SemaphoreSlim _sem = new SemaphoreSlim (3); // Capacity of 3

static void Main()

for (int i = 1; i <= 5; i++) new Thread (Enter).Start (i);

static void Enter (item id)

Console.WriteLine (id + " wants to enter");

_sem.Wait();

Console.WriteLine (identification + " is in!"); // Only 3 threads

Thread.Sleep (1000 * (int) id); // may be here at

Console.WriteLine (id + " is leaving"); // a time.

_sem.Release();

Out Put:

1 wants to enter

1 is in!

2 desires to enter

2 is in!

Three desires to enter

3 is in!

Four wants to enter

five desires to input

1 is leaving

four is in!

2 is leaving

five is in!

If the Sleep assertion turned into instead performing extensive disk I/O, the Semaphore could enhance average performance

by proscribing excessive concurrent hard-drive interest.

A Semaphore, if named, can span techniques inside the identical way as a Mutex.

Q31. What Is Starvation? And What Is A Livelock?

Starvation and livelock are a lot less commonplace a problem than impasse, but are still troubles that every fashion designer of concurrent software is probably to encounter. 

LiveLock:

Livelock takes place whilst all threads are blocked, or are in any other case not able to proceed because of unavailability of required resources, and the non-life of any unblocked thread to make those sources to be had. In phrases of Java API, thread livelock can arise in following situations: 

When all of the threads in a software execute Object.Wait(zero) on an item with zero parameter. The software is stay-locked and can't continue till one or extra threads name Object.Notify() or Object.NotifyAll() at the relevant gadgets. Because all of the threads are blocked, neither call can be made.

When all of the threads in a software are caught in endless loops.

Starvation:

Starvation describes a situation in which a thread is not able to advantage ordinary get right of entry to to shared sources and is not able to make development. This occurs while shared sources are made unavailable for lengthy durations by way of "grasping" threads. For example, assume an object provides a synchronized approach that regularly takes a long time to go back. If one thread invokes this technique regularly, different threads that also want common synchronized get entry to to the identical item will frequently be blocked. Starvation happens whilst one thread can not get entry to the CPU because one or extra different threads are monopolizing the CPU. In Java, thread starvation may be caused by setting thread priorities inappropriately. A lower-precedence thread can be starved by using higher-precedence threads if the better-priority threads do no longer yield control of the CPU every so often. 

Q32. How Can We Scheduled A Thread In C# ?

We can scheduled the  thread with the help of precedence assets of the Thread magnificence.

Q33. What Is Threadlocal Class? How Can It Be Used?

Below are a few key factors approximately ThreadLocal variables 

A thread-local variable efficiently affords a separate replica of its value for each thread that uses it.

ThreadLocal instances are commonly private static fields in lessons that wish to associate kingdom with a thread

In case whilst multiple threads get right of entry to a ThreadLocal example, separate replica of Threadlocal variable is maintained for each thread.

Common use is seen in DAO pattern in which the DAO class can be singleton however the Database connection can be maintained one after the other for every thread. (Per Thread Singleton)

ThreadLocal variable are difficult to understand and I actually have discovered beneath reference links very useful in getting higher know-how on them 

Q34. What Are The Advantage Of Multithreading In C# ?

There are  principal benefit to apply of multithreading in c#. Optimize the usage of laptop resources together with reminiscence. Save time

Q35. What Is Synchronization In Respect To Multi-threading In C#?

With appreciate to multi-threading, synchronization is the capability to control the get right of entry to of more than one threads to shared assets. Without synchronization, it is possible for one Java thread to modify a shared variable whilst some other thread is in the procedure of the usage of or updating same shared variable. This usually leads to misguided conduct or application.

Q36. What Is A Thread Leak? What Does It Mean In C#?

Thread leak is whilst a software does no longer launch references to a thread object properly. Due to this a few Threads do not get rubbish gathered and the range of unused threads grow with time. Thread leak can often motive severe issues on a Java utility for the reason that over a period of time too many threads can be created but no longer launched and may purpose packages to respond sluggish or cling.

Q37. How To Find A Deadlock Has Occurred In Java? How To Detect A Deadlock In Java?

Earlier variations of Java had no mechanism to deal with/stumble on impasse. Since JDK 1.5 there are some effective methods added within the java.Lang.Control package deal to diagnose and discover deadlocks. The java.Lang.Management.ThreadMXBean interface is control interface for the thread machine of the Java virtual gadget. It has  techniques that could leveraged to stumble on impasse in a Java application. 

FindMonitorDeadlockedThreads() - This approach may be used to come across cycles of threads which might be in deadlock waiting to acquire item video display units. It returns an array of thread IDs which are deadlocked waiting on display.

FindDeadlockedThreads() - It returns an array of thread IDs that are deadlocked waiting on display or ownable synchronizers.

Q38. Explain Different Way Of Using Thread?

A Java thread will be implemented through the usage of Runnable interface or through extending the Thread elegance. The Runnable is more high quality, when you are going for multiple inheritance.

Q39. What Is The Difference Between Thread.Begin() & Thread.Run() Method?

Thread.Begin() method (native method) of Thread elegance really does the activity of jogging the Thread.Run() technique in a thread. If we immediately call Thread.Run() technique it's going to executed in equal thread, so does not solve the purpose of creating a new thread.

Q40. What Is The Difference Between Sleep(), Suspend() And Wait() ?

Thread.Sleep() takes the present day thread to a "Not Runnable" kingdom for certain amount of time. The thread holds the monitors it has received. For example, if a thread is running a synchronized block or approach and sleep method is known as then no other thread can be capable of enter this block or approach. The drowsing thread can awaken while a few other thread calls t.Interrupt on it. Note that sleep is a static method, that me it continually influences the current thread (the only executing sleep technique). A commonplace mistake is making an attempt to name t2.Sleep() wherein t2 is a one-of-a-kind thread; even then, it's far the current thread that will sleep, now not the t2 thread. Thread.Droop() is deprecated method. Its feasible to send other threads into suspended nation by means of making a droop technique name. In suspended country a thread continues all its video display units and can't be interrupted. This may additionally cause deadlocks consequently it has been deprecated. Item.Wait() name also takes the modern thread right into a "Not Runnable" nation, just like sleep(), however with a moderate change. Wait technique is invoked on a lock object, now not thread. 

Here is the series of operations you could suppose 

A thread T1 is already strolling a synchronized block with a lock on item - let's imagine "lockObject"

Another thread T2 involves execute the synchronized block and find that its already obtained.

Now T2 calls lockObject.Wait() technique for waiting on lock to be release by way of T1 thread.

T1 thread finishes all its synchronized block work.

T1 thread calls lockObject.NotifyAll() to notify all ready threads that its completed the use of the lock.

Since T2 thread is first in the queue of waiting it acquires the lock and starts processing.

Q41. What Is The Meaning Of Mutex?

A Mutex is sort of a C# lock, however it can work throughout multiple techniques. In other phrases, Mutex can be computer-huge as

well as application-extensive. 

With a Mutex class, you call the WaitOne technique to lock and ReleaseMutex to unencumber. Closing or disposing a Mutex routinely releases it. Just as with the lock assertion, a Mutex may be launched best from the identical thread that acquired it. A commonplace use for a pass-process Mutex is to make certain that only one example of a program can run at a time. Here’s the way it’s completed:

magnificence OneAtATimePlease

static void Main()

// Naming a Mutex makes it to be had pc-wide. Use a name that's

// specific on your corporation and application (e.G., encompass your URL).

The use of (var mutex = new Mutex (fake, "oreilly.Com OneAtATimeDemo"))

// Wait some seconds if contended, in case some other instance

// of the program is still in the technique of shutting down.

If (!Mutex.WaitOne (TimeSpan.FromSeconds (3), fake))

Console.WriteLine ("Another instance of the app is going for walks. Bye!");

return;

RunProgram();

static void RunProgram()

Console.WriteLine ("Running. Press Enter to exit");

Console.ReadLine();




CFG