Top L Coffee Thread Interview Questions Answers For Experienced

You move to whatsoever Java interview, senior or junior, sense or freshers,  you are saltation to consider a duet of questions from the thread, concurrency, in addition to multi-threading. In fact, this built-in concurrency back upwards is i of the strongest points of Java programming linguistic communication in addition to helped it to gain popularity amidst enterprise earth in addition to programmers equally. Most of lucrative Java developer seat demands excellent pith Java multi-threading skills and sense inwards developing, debugging in addition to tuning high-performance depression latency concurrent Java applications. This is the reason, it is i of the most sought after science on Java interviews. The multithreading in addition to concurrency are also hard to master copy concept in addition to alone practiced developers amongst company sense tin effectively bargain amongst concurrency issues.

In a typical Java interview, Interviewer like shooting fish in a barrel starts from basic concepts of Thread past times asking questions like, why you lot demand threads, how to do threads, which i is improve way to do threads e.g. by extending thread degree or implementing Runnable and hence like shooting fish in a barrel goes into Concurrency issues, challenges faced during evolution of concurrent Java applications, Java retention model, higher-order concurrency utilities introduced inwards JDK 1.5, principles in addition to blueprint patterns of concurrent Java applications, classical multi-threading problems e.g. producer-consumer, dining philosopher, reader-writer or but bounded buffer problems.

Since its also non plenty exactly to know basics of threading, you lot must know how to bargain amongst concurrency problems e.g. deadlock, race conditions, retention inconsistency in addition to diverse thread security related issues. These skills are thoroughly acquire tested past times presenting diverse multi-threading in addition to concurrency problems.


Many Java developers are used to alone aspect in addition to read interview questions before going for the interview, which is non bad but you lot should non live as good far away. Also collecting questions in addition to going through the same exercise is as good much fourth dimension consuming, that's why I have got created this listing of top 50 Java multi-threading in addition to concurrency related questions, collected from diverse interviews. I am alone going to add together novel in addition to recent interview questions as in addition to when I am going to discovery them.

Though you lot demand practiced cognition in addition to company sense to do good on Java interviews focused on advanced multithreading in addition to concurrency skill, I strongly recommend Java programmers to read Effective Java in addition to Java Concurrency inwards Practice twice before going to interview. They do non alone assist you lot to reply questions improve but also assist you lot to nowadays your thought clearly.

By the way, I have got non provided answers to some questions here, Why? because I aspect most of Java developer to know the answers to this interrogation in addition to if not, also answers are widely available past times using Google. If you lot don't discovery the reply to whatsoever exceptional question, you lot tin ever inquire me inwards the comments section. You tin fifty-fifty discovery answers to few questions on the link provided or my before post Top 12 Java Thread Questions amongst Answers.



50 Interview questions from Java Multi-threading in addition to Concurrency

Here is our listing of top questions from Java thread, concurrency, in addition to multi-threading. You tin work this listing to prepare good for your Java interview.


1)  What is Thread inwards Java? (answer)
The thread is an independent path of execution. It's way to lead payoff of multiple CPU available inwards a machine. By employing multiple threads you lot tin speed upwards CPU saltation task. For example, if i thread takes 100 milliseconds to do a job, you lot tin work 10 thread to cut down that labor into 10 milliseconds. Java provides first-class back upwards for multithreading at the linguistic communication level, in addition to it's also i of the strong selling points.


2)  What is the divergence betwixt Thread in addition to Process inwards Java? (answer)
The thread is a subset of Process, inwards other words, i procedure tin comprise multiple threads. Two procedure runs on dissimilar retention space, but all threads portion same retention space. Don't confuse this amongst stack memory, which is dissimilar for the dissimilar thread in addition to used to shop local information to that thread. For to a greater extent than exceptional consider the answer.


3)  How do you lot implement Thread inwards Java? (answer)
At the linguistic communication level, at that topographic point are 2 ways to implement Thread inwards Java. An instance of java.lang.Thread stand upwards for a thread but it needs a labor to execute, which is an instance of interface java.lang.Runnable. Since Thread class itself implement Runnable, you lot tin override run() method either past times extending Thread degree or exactly implementing Runnable interface. For detailed reply in addition to give-and-take consider this article.


4)  When to work Runnable vs Thread inwards Java? (answer)
This is a follow-up of previous multi-threading interview question. As nosotros know nosotros tin implement thread either past times extending Thread class or implementing Runnable interface, the interrogation arise, which i is improve in addition to when to work one? This interrogation volition live like shooting fish in a barrel to reply if you lot know that Java programming linguistic communication doesn't back upwards multiple inheritances of class, but it allows you lot to implement multiple interfaces. Which means, it's improve to implement Runnable then extends Thread if you lot also desire to extend some other degree e.g. Canvas or CommandListener. For to a greater extent than points in addition to give-and-take you lot tin also refer this post.



6)  What is the divergence betwixt start() in addition to run() method of Thread class?  (answer)
One of draw a fast i on Java interrogation from early on days, but yet practiced plenty to differentiate betwixt shallow agreement of Java threading model start() method is used to start newly created thread, patch start() internally calls run() method, at that topographic point is divergence calling run() method directly. When you lot invoke run() as normal method, its called inwards the same thread, no novel thread is started, which is the instance when you lot telephone phone start() method. Read this answer for much to a greater extent than detailed discussion.


7)  What is the divergence betwixt Runnable in addition to Callable inwards Java? (answer)
Both Runnable in addition to Callable stand upwards for labor which is intended to live executed inwards a separate thread. Runnable is at that topographic point from JDK 1.0 patch Callable was added on JDK 1.5. Main divergence betwixt these 2 is that Callable's call() method tin render value in addition to throw Exception, which was non possible amongst Runnable's run() method. Callable render Future object, which tin agree the final result of computation. See my blog post on the same topic for a to a greater extent than in-depth reply to this question.


8)  What is the divergence betwixt CyclicBarrier in addition to CountDownLatch inwards Java?  (answer)
Though both CyclicBarrier in addition to CountDownLatch hold off for number of threads on i or to a greater extent than events, the primary divergence betwixt them is that you lot tin non re-use CountDownLatch once count reaches to zero, but you lot tin reuse same CyclicBarrier even after barrier is broken.  See this answer for few to a greater extent than points in addition to sample code example.


9)  What is Java Memory model? (answer)
Java Memory model is laid of rules in addition to guidelines which allows Java programs to bear deterministically across multiple retention architecture, CPU, in addition to operating system. It's especially of import inwards instance of multi-threading. Java Memory Model provides some guarantee on which changes made past times i thread should live visible to others, i of them is happens-before relationship. This human relationship defines several rules which allows programmers to anticipate in addition to argue behaviour of concurrent Java programs. For example, happens-before human relationship guarantees :
  • Each activeness inwards a thread happens-before every activeness inwards that thread that comes afterwards inwards the computer program order, this is known as computer program guild rule.
  • An unlock on a monitor lock happens-before every subsequent lock on that same monitor lock, also known as Monitor lock rule.
  • A write to a volatile champaign happens-before every subsequent read of that same field, known as Volatile variable rule.
  • A telephone phone to Thread.start on a thread happens-before whatsoever other thread detects that thread has terminated, either past times successfully render from Thread.join() or past times Thread.isAlive() returning false, also known as Thread start rule.
  • A thread calling interrupt on some other thread happens-before the interrupted thread detects the interrupt( either past times having InterruptedException thrown, or invoking isInterrupted or interrupted), popularly known as Thread Interruption rule.
  • The terminate of a constructor for an object happens-before the start of the finalizer for that object, known as Finalizer rule.
  • If Influenza A virus subtype H5N1 happens-before B, in addition to B happens-before C, hence Influenza A virus subtype H5N1 happens-before C, which way happens-before guarantees Transitivity.
I strongly propose reading Chapter sixteen of Java Concurrency inwards Practice to sympathise Java Memory model inwards to a greater extent than detail.




10) What is volatile variable inwards Java? (answer)
volatile is a special modifier, which tin alone live used amongst instance variables. In concurrent Java programs, changes made past times multiple threads on instance variables is non visible to other inwards absence of whatsoever synchronizers e.g. synchronized keyword or locks. Volatile variable guarantees that a write volition hap before whatsoever subsequent read: as stated: "volatile variable rule" inwards previous question. Read this answer to larn to a greater extent than nigh volatile variable in addition to when to work them.


11) What is thread-safety? is Vector a thread-safe class? (Yes, consider details)
Thread-safety is a holding of an object or code which guarantees that if executed or used past times multiple threads inwards whatsoever fashion e.g. read vs write it volition bear as expected. For example, a thread-safe counter object volition non immature lady whatsoever count if same instance of that counter is shared amidst multiple threads. Apparently, you lot tin also separate collection classes inwards 2 category, thread-safe in addition to non-thread-safe. Vector is indeed a thread-safe degree in addition to it achieves thread-safety past times synchronizing methods which modify nation of Vector, on the other hand, its counterpart ArrayList is non thread-safe.


12) What is race status inwards Java? Given i example?  (answer)
Race status are drive of some subtle programming bugs when Java programs are exposed to concurrent execution environment. As the get upwards suggests, a race status occurs due to race betwixt multiple threads, if a thread which is supposed to execute showtime lost the race in addition to executed second, behaviour of code changes, which surface as non-deterministic bugs. This is i of the hardest bugs to discovery in addition to re-produce because of random nature of racing betwixt threads. One illustration of race status is out-of-order processing, consider this answer for some to a greater extent than illustration of race weather inwards Java programs.


13) How to halt a thread inwards Java? (answer(answer)
I ever said that Java provides rich APIs for everything but ironically Java doesn't supply a surely shot way of stopping thread. There was some command methods inwards JDK 1.0 e.g. stop(), suspend() in addition to resume() which was deprecated inwards afterwards releases due to potential deadlock threats, from hence Java API designers has non made whatsoever endeavor to supply a consistent, thread-safe in addition to elegant way to halt threads. Programmers mainly rely on the fact that thread stops automatically as presently as they destination execution of run() or call() method. To manually stop, programmers either lead payoff of volatile boolean variable in addition to banking concern check inwards every iteration if run method has loops or interrupt threads to abruptly cancel tasks. See this tutorial for sample code of stopping thread inwards Java.



14) What happens when an Exception occurs inwards a thread? (answer)
This is i of the practiced tricky Java question I have got seen inwards interviews. In elementary words, If non caught thread volition die, if an uncaught exception handler is registered hence it volition acquire a telephone phone back. Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. When a thread is nigh to terminate due to an uncaught exception the Java Virtual Machine volition query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() in addition to volition invoke the handler's uncaughtException() method, passing the thread in addition to the exception as arguments.


15) How do you lot portion information betwixt 2 thread inwards Java? (answer)
You tin portion information betwixt threads past times using shared object, or concurrent information construction similar BlockingQueue. See this tutorial to learn  inter-thread communication inwards Java. It implements Producer consumer pattern using hold off in addition to notify methods, which involves sharing objects betwixt 2 threads.

you are saltation to consider a duet of questions from the thread Top 50 Java Thread Interview Questions Answers for Experienced


16) What is the divergence betwixt notify in addition to notifyAll inwards Java? (answer)
This is some other tricky questions from pith Java interviews, since multiple threads tin hold off on unmarried monitor lock, Java API designer provides method to inform alone i of them or all of them, in i lawsuit waiting status changes, but they supply one-half implementation. There notify() method doesn't supply whatsoever way to pick out a exceptional thread, that's why its alone useful when you lot know that at that topographic point is alone i thread is waiting. On the other hand, notifyAll() sends notification to all threads in addition to allows them to compete for locks, which ensures that at-least i thread volition move on further. See my blog post on similar topic for a to a greater extent than detailed reply in addition to code example.


17) Why wait, notify in addition to notifyAll are non within thread class?  (answer)
This is a blueprint related question, which checks what candidate thinks nigh existing organisation or does he ever thought of something which is hence mutual but looks in-appropriate at first. In guild to reply this question, you lot have got to give some reasons why it brand sense for these 3 method to live inwards Object class, in addition to why non on Thread class. One argue which is obvious is that Java provides lock at object plane non at thread level. Every object has lock, which is acquired past times thread. Now if thread needs to hold off for surely lock it brand sense to telephone phone wait() on that object rather than on that thread. Had wait() method declared on Thread class, it was non clear that for which lock thread was waiting. In short, since wait, notify in addition to notifyAll operate at lock level, it brand sense to defined it on object degree because lock belongs to object. You tin also consider this article for to a greater extent than elaborate reply of this question.


18) What is ThreadLocal variable inwards Java?  (answer)
ThreadLocal variables are special form of variable available to Java programmer. Just similar instance variable is per instance, ThreadLocal variable is per thread. It's a overnice way to range thread-safety of expensive-to-create objects, for illustration you lot tin brand SimpleDateFormat thread-safe using ThreadLocal. Since that degree is expensive, its non practiced to work it inwards local scope, which requires separate instance on each invocation. By providing each thread their ain copy, you lot shoot 2 birds amongst i arrow. First, you lot cut down number of instance of expensive object past times reusing fixed number of instances, in addition to Second, you lot range thread-safety without paying toll of synchronization or immutability. Another practiced illustration of thread local variable is ThreadLocalRandom class, which reduces number of instances of expensive-to-create Random object inwards multi-threading environment. See this answer to larn to a greater extent than nigh thread local variables inwards Java.


19) What is FutureTask inwards Java? (answer)
FutureTask represents a cancellable asynchronous computation inwards concurrent Java application. This degree provides a base of operations implementation of Future, amongst methods to start in addition to cancel a computation, query to consider if the computation is complete, in addition to yell upwards the final result of the computation. The final result tin alone live retrieved when the computation has completed; the acquire methods volition block if the computation has non yet completed. A FutureTask object tin live used to wrap a Callable or Runnable object. Since FutureTask also implements Runnable, it tin live submitted to an Executor for execution.


20) What is the divergence betwixt the interrupted() in addition to isInterrupted() method inwards Java? (answer)
Main divergence betwixt interrupted() in addition to isInterrupted() is that onetime clears the interrupt status patch afterwards does not. The interrupt machinery inwards Java multi-threading is implemented using an internal flag known as the interrupt status. Interrupting a thread past times calling Thread.interrupt() sets this flag. When interrupted thread checks for an interrupt past times invoking the static method Thread.interrupted(), interrupt status is cleared. The non-static isInterrupted() method, which is used past times i thread to query the interrupt status of another, does non alter the interrupt status flag. By convention, whatsoever method that exits past times throwing an InterruptedException clears interrupt status when it does so. However, it's ever possible that interrupt status volition forthwith live laid again, past times some other thread invoking interrupt



21) Why hold off in addition to notify method are called from synchronized block? (answer)
Main argue for calling hold off in addition to notify method from either synchronized block or method is that it made mandatory past times Java API. If you lot don't telephone phone them from synchronized context, your code volition throw IllegalMonitorStateException. Influenza A virus subtype H5N1 to a greater extent than subtle argue is to avoid the race status betwixt hold off in addition to notify calls. To larn to a greater extent than nigh this, banking concern check my similarly titled post here.


22) Why should you lot banking concern check status for waiting inwards a loop? (answer)
Its possible for a waiting thread to have simulated alerts in addition to spurious wake upwards calls, if it doesn't banking concern check the waiting status inwards loop, it volition but acquire out fifty-fifty if status is non met. As such, when a waiting thread wakes up, it cannot assume that the nation it was waiting for is yet valid. It may have got been valid inwards the past, but the nation may have got been changed after the notify() method was called in addition to before the waiting thread woke up. That's why it ever improve to telephone phone wait() method from loop, you lot tin fifty-fifty do template for calling hold off in addition to notify inwards Eclipse. To larn to a greater extent than nigh this question, I would recommend you lot to read Effective Java items on thread in addition to synchronization.


23) What is the divergence betwixt synchronized in addition to concurrent collection inwards Java? (answer)
Though both synchronized in addition to concurrent collection provides thread-safe collection suitable for multi-threaded in addition to concurrent access, afterwards is to a greater extent than scalable than former. Before Java 1.5, Java programmers alone had synchronized collection which becomes rootage of tilt if multiple thread access them concurrently, which hampers scalability of system. Java five introduced concurrent collections similar ConcurrentHashMap, which non alone provides thread-safety but also improves scalability past times using modern techniques similar lock stripping in addition to partitioning internal table. See this answer for to a greater extent than differences betwixt synchronized in addition to concurrent collection inwards Java.


24) What is the divergence betwixt Stack in addition to Heap inwards Java? (answer)
Why does someone this interrogation as role of multi-threading in addition to concurrency? because Stack is a retention expanse which is closely associated amongst threads. To reply this question, both stack in addition to heap are specific memories inwards Java application. Each thread has their ain stack, which is used to shop local variables, method parameters in addition to telephone phone stack. Variable stored inwards i Thread's stack is non visible to other. On some other hand, the heap is a mutual retention expanse which is shared past times all threads. Objects whether local or at whatsoever plane is created within heap. To improve performance thread tends to cache values from heap into their stack, which tin do problems if that variable is modified past times to a greater extent than than i thread, this is where volatile variables come upwards into the picture. volatile propose threads read the value of variable ever from primary memory. See this article for learning to a greater extent than nigh stack in addition to heap inwards Java to reply this interrogation inwards greater detail.


you are saltation to consider a duet of questions from the thread Top 50 Java Thread Interview Questions Answers for Experienced

25) What is thread pool? Why should you lot thread puddle inwards Java?  (answer)
Creating thread is expensive inwards damage of fourth dimension in addition to resource. If you lot do thread at fourth dimension of asking processing it volition irksome downwards your response time, also at that topographic point is alone a express number of threads a procedure tin create. To avoid both of these issues, a puddle of thread is created when application starts-up in addition to threads are reused for asking processing. This puddle of thread is known as "thread pool" in addition to threads are known as worker thread. From JDK 1.5 release, Java API provides Executor framework, which allows you lot to do dissimilar types of thread pools e.g. unmarried thread pool, which procedure i labor at a time, fixed thread puddle (a puddle of fixed number of threads) or cached thread puddle (an expandable thread puddle suitable for applications amongst many brusque lived tasks). See this article to learn to a greater extent than nigh thread pools inwards Java to prepare detailed reply of this question.


26) Write code to solve Producer Consumer job inwards Java? (answer)
Most of the threading job you lot solved inwards the existent earth are of the category of Producer consumer pattern, where i thread is producing labor in addition to some other thread is consuming that. You must know how to do inter thread communication to solve this problem. At the lowest level, you lot tin work hold off in addition to notify to solve this problem, in addition to at a high level, you lot tin leverage Semaphore or BlockingQueue to implement Producer consumer pattern, as shown inwards this tutorial.


27) How do you lot avoid deadlock inwards Java? Write Code?
you are saltation to consider a duet of questions from the thread Top 50 Java Thread Interview Questions Answers for Experienced
Deadlock is a status inwards which 2 threads hold off for each other to lead activeness which allows them to movement further. It's a serious number because when it hap your computer program hangs in addition to doesn't do the labor it is intended for. In guild for deadlock to happen, next 4 weather must live true:

  • Mutual Exclusion : At to the lowest degree i resources must live held inwards a non-shareable mode. Only i procedure tin work the resources at whatsoever given instant of time.
  • Hold in addition to Wait: Influenza A virus subtype H5N1 procedure is currently holding, at least, i resources in addition to requesting additional resources which are existence held past times other processes.
  • No Pre-emption: The operating organisation must non de-allocate resources in i lawsuit they have got been allocated; they must live released past times the holding procedure voluntarily.
  • Circular Wait: A procedure must live waiting for a resources which is existence held past times some other process, which inwards plough is waiting for the showtime procedure to loose the resource.

The easiest way to avoid deadlock is to forestall Circular wait, in addition to this tin live done past times acquiring locks inwards a exceptional guild in addition to releasing them inwards contrary guild hence that a thread tin alone move on to acquire a lock if it held the other one. Check this tutorial for the actual code illustration in addition to detailed give-and-take on techniques for avoiding deadlock inwards Java.


28) What is the divergence betwixt livelock in addition to deadlock inwards Java? (answer)
This interrogation is extension of previous interview question. Influenza A virus subtype H5N1 livelock is similar to a deadlock, except that the states of the threads or processes involved inwards the livelock constantly alter amongst regard to i another, without whatsoever i progressing further. Livelock is a special instance of resources starvation. Influenza A virus subtype H5N1 real-world illustration of livelock occurs when 2 people encounter inwards a narrow corridor, in addition to each tries to live polite past times moving aside to allow the other pass, but they terminate upwards swaying from side to side without making whatsoever progress because they both repeatedly movement the same way at the same time. In short, the primary divergence betwixt livelock in addition to deadlock is that inwards onetime nation of procedure alter but no progress is made.



29) How do you lot banking concern check if a Thread holds a lock or not? (answer)
I didn't fifty-fifty know that you lot tin banking concern check if a Thread already holds lock before this interrogation hits me inwards a telephonic circular of Java interview. There is a method called holdsLock() on java.lang.Thread, it returns truthful if in addition to alone if the electrical flow thread holds the monitor lock on the specified object. You tin also banking concern check this article for the to a greater extent than detailed answer.


30) How do you lot lead thread dump inwards Java? (answer)
There are multiple ways to lead thread dump of Java procedure depending upon operating system. When you lot lead thread dump, JVM dumps nation of all threads inwards log files or criterion fault console. In windows you lot tin work Ctrl + Break cardinal combination to lead thread dump, on Linux you lot tin work kill -3 command for same. You tin also work a tool called jstack for taking thread dump, it operate on procedure id, which tin live institute using some other tool called jps.


31) Which JVM parameter is used to command stack size of a thread? (answer)
This is the elementary one, -Xss parameter is used to command stack size of Thread inwards Java. You tin consider this list of JVM options to larn to a greater extent than nigh this parameter.


32) What is the divergence betwixt synchronized in addition to ReentrantLock inwards Java? (answer)
There were days when the alone way to supply mutual exclusion inwards Java was via synchronized keyword, but it has several shortcomings e.g. you lot tin non extend lock beyond a method or block boundary, you lot tin non surrender trying for a lock etc. Java five solves this job past times providing to a greater extent than sophisticated command via Lock interface. ReentrantLock is a mutual implementation of Lock interface in addition to provides re-entrant mutual exclusion Lock amongst the same basic behaviour in addition to semantics as the implicit monitor lock accessed using synchronized methods in addition to statements, but amongst extended capabilities. See this article larn nigh those capabilities in addition to some to a greater extent than differences betwixt synchronized vs ReentrantLock inwards Java.


33) There are 3 threads T1, T2, in addition to T3? How do you lot ensure sequence T1, T2, T3 inwards Java? (answer)
Sequencing inwards multi-threading tin live achieved past times dissimilar way but you lot tin but work the join() method of thread degree to start a thread when some other i has finished its execution. To ensure 3 threads execute you lot demand to start the lastly i showtime e.g. T3 in addition to hence telephone phone bring together methods inwards contrary guild e.g. T3 calls T2. bring together in addition to T2 calls T1.join, these ways T1 volition destination showtime in addition to T3 volition destination last. To larn to a greater extent than nigh bring together method, consider this tutorial.


34) What does yield method of Thread degree do? (answer)
Yield method is i way to asking electrical flow thread to relinquish CPU hence that other thread tin acquire a lead chances to execute. Yield is a static method in addition to alone guarantees that electrical flow thread volition relinquish the CPU but doesn't say anything nigh which other thread volition acquire CPU. Its possible for the same thread to acquire CPU dorsum in addition to start its execution again. See this article to larn to a greater extent than nigh yield method and to reply this interrogation better.


35) What is the concurrency plane of ConcurrentHashMap inwards Java? (answer)
ConcurrentHashMap achieves it's scalability in addition to thread-safety past times partitioning actual map into a number of sections. This partitioning is achieved using concurrency level. Its optional parameter of ConcurrentHashMap constructor in addition to it's default value is 16. The tabular array is internally partitioned to assay to permit the indicated number of concurrent updates without contention. To larn to a greater extent than nigh concurrency plane in addition to internal resizing, consider my post How ConcurrentHashMap industrial plant inwards Java.



36) What is Semaphore inwards Java? (answer)
Semaphore inwards Java is a novel form of synchronizer. It's a counting semaphore. Conceptually, a semaphore maintains a laid of permits. Each acquire() blocks if necessary until a permit is available, in addition to hence takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore exactly keeps a count of the number available in addition to acts accordingly. Semaphore is used to protect an expensive resources which is available inwards fixed number e.g. database connective inwards the pool. See this article to larn to a greater extent than nigh counting Semaphore inwards Java.


37) What happens if you lot submit a labor when the queue of the thread puddle is already filled? (answer)
This is some other tricky interrogation on my list. Many programmers volition think that it volition block until a labor is cleared but its true. ThreadPoolExecutor's submit() method throws RejectedExecutionException if the labor cannot live scheduled for execution.


38) What is the divergence betwixt the submit() in addition to execute() method thread puddle inwards Java? (answer)
Both methods are ways to submit a labor to thread pools but at that topographic point is a slight divergence betwixt them. execute(Runnable command) is defined inwards Executor interface in addition to executes given labor inwards future, but to a greater extent than importantly, it does non render anything. Its render type is void. On other mitt submit() is an overloaded method, it tin lead either Runnable or Callable labor in addition to tin render Future object which tin agree the pending final result of computation. This method is defined on ExecutorService interface, which extends Executor interface, in addition to every other thread puddle degree e.g. ThreadPoolExecutor or ScheduledThreadPoolExecutor gets these methods. To larn to a greater extent than nigh thread pools you lot tin banking concern check this article.


39) What is blocking method inwards Java? (answer)
Influenza A virus subtype H5N1 blocking method is a method which blocks until the labor is done, for example, accept() method of ServerSocket blocks until a customer is connected. hither blocking way command volition non render to the caller until the labor is finished. On the other hand, at that topographic point is an asynchronous or non-blocking method which returns fifty-fifty before the labor is finished. To larn to a greater extent than nigh blocking method consider this answer.


40) Is Swing thread-safe? What do you lot hateful past times Swing thread-safe? (answer)
You tin but this interrogation as No, Swing is non thread-safe, but you lot have got to explicate what you lot hateful past times that fifty-fifty if the interviewer doesn't inquire nigh it. When nosotros say swing is non thread-safe nosotros usually refer its component, which tin non live modified inwards multiple threads. All update to GUI components has to live done on AWT thread, in addition to Swing provides synchronous in addition to asynchronous callback methods to schedule such updates. You tin also read my article to larn to a greater extent than nigh swing in addition to thread-safety to improve reply this question. Even side past times side 2 questions are also related to this concept.


41) What is the divergence betwixt invokeAndWait in addition to invokeLater inwards Java? (answer)
These are 2 methods Swing API provides Java developers for updating GUI components from threads other than Event dispatcher thread. InvokeAndWait() synchronously update GUI component, for example, a progress bar, in i lawsuit progress is made, the bar should also live updated to reverberate that change. If progress is tracked inwards a dissimilar thread, it has to telephone phone invokeAndWait() to schedule an update of that constituent past times Event dispatcher thread. On some other hand, invokeLater() is an asynchronous telephone phone to update components. You tin also refer this answer for to a greater extent than points.


42) Which method of Swing API are thread-safe inwards Java? (answer)
This interrogation is in i lawsuit again related to swing in addition to thread-safety though components are non thread-safe at that topographic point is a surely method which tin live safely called from multiple threads. I know nigh repaint(), in addition to revalidate() existence thread-safe but at that topographic point are other methods on dissimilar swing components e.g. setText() method of JTextComponent, insert() in addition to append() method of JTextArea class.


43) How to do an Immutable object inwards Java? (answer)
This interrogation mightiness non aspect related to multi-threading in addition to concurrency, but it is. Immutability helps to simplify already complex concurrent code inwards Java. Since immutable object tin live shared without whatsoever synchronization its really dearest to Java developers. Core value object, which is meant to live shared amidst thread should live immutable for performance in addition to simplicity. Unfortunately at that topographic point is no @Immutable tone inwards Java, which tin brand your object immutable, hard move must live done past times Java developers. You demand to maintain basics similar initializing nation inwards constructor, no setter methods, no leaking of reference, keeping separate re-create of mutable object to do Immutable object. For measurement past times measurement guide consider my post, how to brand an object Immutable inwards Java. This volition give you lot plenty textile to reply this interrogation amongst confidence.


44) What is ReadWriteLock inwards Java? (answer)
In general, read write lock is the final result of lock stripping technique to improve the performance of concurrent applications. In Java, ReadWriteLock is an interface which was added inwards Java five release. A ReadWriteLock maintains a pair of associated locks, i for read-only operations in addition to i for writing. The read lock may live held simultaneously past times multiple reader threads, hence long as at that topographic point are no writers. The write lock is exclusive. If you lot desire you lot tin implement this interface amongst your ain laid of rules, otherwise you lot tin use ReentrantReadWriteLock, which comes along amongst JDK in addition to supports a maximum of 65535 recursive write locks in addition to 65535 read locks.


45) What is busy spin inwards multi-threading? (answer)
Busy spin is a technique which concurrent programmers employ to brand a thread hold off on surely condition. Unlike traditional methods e.g. wait(), sleep() or yield() which all involves relinquishing CPU control, this method does non relinquish CPU, instead it the exactly runs empty loop. Why would someone do that? to save CPU caches. In a multi-core system, it's possible for a paused thread to resume on a dissimilar core, which way rebuilding cache again. To avoid toll of rebuilding cache, programmer prefer to hold off for much smaller fourth dimension doing busy spin. You tin also consider this answer to larn to a greater extent than nigh this question.



46) What is the divergence betwixt the volatile in addition to atomic variable inwards Java? (answer)
This is an interesting interrogation for Java programmer, at first, volatile in addition to atomic variable aspect really similar, but they are different. Volatile variable provides you lot happens-before guarantee that a write volition hap before whatsoever subsequent write, it doesn't guarantee atomicity. For illustration count++ performance volition non move atomic exactly past times declaring count variable as volatile. On the other mitt AtomicInteger class provides atomic method to perform such chemical compound performance atomically e.g. getAndIncrement() is atomic replacement of increment operator. It tin live used to atomically increment electrical flow value past times one. Similarly you lot have got atomic version for other information type in addition to reference variable as well.


47) What happens if a thread throws an Exception within synchronized block? (answer)
This is i to a greater extent than tricky interrogation for average Java programmer, if he tin convey the fact nigh whether lock is released or non is a cardinal indicator of his understanding. To reply this question, no affair how you lot be synchronized block, either usually past times finishing execution or abruptly past times throwing exception, thread releases the lock it acquired patch entering that synchronized block. This is genuinely i of the reasons I similar synchronized block over lock interface, which requires explicit attending to loose lock, to a greater extent than oftentimes than non this is achieved past times releasing the lock inwards a finally block.


48) What is double checked locking of Singleton? (answer)
This is i of the really pop interrogation on Java interviews, in addition to despite its popularity, chances of candidate answering this interrogation satisfactory is alone 50%. Half of the time, they failed to write code for double checked locking in addition to one-half of the fourth dimension they failed how it was broken in addition to fixed on Java 1.5. This is genuinely an old way of creating thread-safe singleton, which tries to optimize performance past times alone locking when Singleton instance is created showtime time, but because of complexity in addition to the fact it was broken for JDK 1.4,  I personally don't similar it. Anyway, fifty-fifty if you lot non prefer this approach its practiced to know from interview dot of view. Since this interrogation deserve a detailed answer, I have got answered inwards a separate post, you lot tin read my post how double checked locking on Singleton works to larn to a greater extent than nigh it.


49) How to do thread-safe Singleton inwards Java? (answer)
This interrogation is genuinely follow-up of the previous question. If you lot say you lot don't similar double checked locking hence Interviewer is saltation to inquire nigh alternative ways of creating thread-safe Singleton class. There are genuinely man, you lot tin lead payoff of degree loading in addition to static variable initialization characteristic of JVM to do instance of Singleton, or you lot tin leverage powerful enumeration type inwards Java to do Singleton. I genuinely preferred that way, you lot tin also read this article to larn to a greater extent than nigh it in addition to consider some sample code.


50) List downwards 3 multi-threading best exercise you lot follow? (answer)
This is my favorite interrogation because I believe that you lot must follow surely best practices patch writing concurrent code which helps inwards performance, debugging in addition to maintenance. Following are 3 best practices, I think an average Java programmer should follow:
  • Always give meaningful get upwards to your threadThis goes a long way to discovery a põrnikas or delineate an execution inwards concurrent code. OrderProcessor, QuoteProcessor or TradeProcessor is much improve than Thread-1. Thread-2 in addition to Thread-3. The get upwards should say nigh labor done past times that thread. All major framework in addition to fifty-fifty JDK follow this best practice.
  • Avoid locking or Reduce orbit of Synchronization
    Locking is costly in addition to context switching is fifty-fifty costlier. Try to avoid synchronization in addition to locking as much as possible in addition to at a bare minimum, you lot should cut down critical section. That's why I prefer synchronized block over synchronized method because it gives you lot absolute command on the orbit of locking.
  • Prefer Synchronizers over hold off in addition to notify
    Synchronizers similar CountDownLatch, Semaphore, CyclicBarrier or Exchanger simplifies coding. It's really hard to implement complex command flow correct using hold off in addition to notify. Secondly, these classes are written in addition to maintained past times best inwards concern in addition to at that topographic point is practiced lead chances that they are optimized or replaced past times improve performance code inwards subsequent JDK releases. By using higher plane synchronization utilities, you lot automatically acquire all these benefits.
  • Prefer Concurrent Collection over Synchronized Collection
    This is some other elementary best exercise which is like shooting fish in a barrel to follow but reap practiced benefits. Concurrent collection are to a greater extent than scalable than their synchronized counterpart, that's why its improve to work them patch writing concurrent code. So side past times side fourth dimension if you lot demand map, think nigh ConcurrentHashMap before thinking Hashtable. See my article Concurrent Collections inwards Java, to larn to a greater extent than nigh modern collection classes in addition to how to brand best work of them.



51) How do you lot strength to start a Thread inwards Java? (answer)
This interrogation is similar how do you lot strength garbage collection inwards Java, at that topographic point is no way though you lot tin brand a asking using System.gc() but it's non guaranteed. On Java multi-threading at that topographic point is absolutely no way to strength start a thread, this is controlled past times thread scheduler in addition to Java exposes no API to command thread schedule. This is yet a random chip inwards Java.


52) What is the fork-join framework inwards Java? (answer)
The fork-join framework, introduced inwards JDK vii is a powerful tool available to Java developer to lead payoff of multiple processors of modern twenty-four hr flow servers. It is designed for move that tin live broken into smaller pieces recursively. The goal is to work all the available processing powerfulness to heighten the performance of your application. One important payoff of The fork/join framework is that it uses a work-stealing algorithm. Worker threads that run out of things to do tin steal tasks from other threads that are yet busy. See this article for the much to a greater extent than detailed reply to this question.


53) What is the divergence betwixt calling wait() in addition to sleep() method inwards Java multi-threading? (answer)
Though both hold off in addition to slumber innovate some cast of interruption inwards Java application, they are the tool for dissimilar needs. Wait method is used for inter-thread communication, it relinquishes lock if waiting for a status is truthful in addition to hold off for notification when due to an activeness of some other thread waiting status becomes false. On the other mitt sleep() method is exactly to relinquish CPU or halt execution of electrical flow thread for specified fourth dimension duration. Calling slumber method doesn't loose the lock held past times the electrical flow thread. You tin also lead aspect at this article to reply this interrogation amongst to a greater extent than details.


That's all on this listing of top 50 Java multi-threading in addition to concurrency interview questions. I have got non shared answers of all the questions but provided plenty hints in addition to links to explore farther in addition to discovery answers past times yourselves. As I said, allow me know if you lot don't discovery reply of whatsoever exceptional interrogation in addition to I volition add together reply here.

You tin work this listing to non alone to prepare for your pith Java in addition to programming interviews but also to banking concern check your cognition nigh basics of threads, multi-threading, concurrency, blueprint patterns in addition to threading issues similar race conditions, deadlock in addition to thread security problems.

My intention is to brand this listing of interrogation as the woman bring upwards of all listing of Java Multi-threading questions, but this tin non live done without your help. You tin also portion whatsoever interrogation amongst us, which has been asked to you lot or whatsoever interrogation for which you lot yet to discovery an answer.

This master copy listing is as useful to Java developers of all levels of experience. You tin read through this listing fifty-fifty if you lot have got 2 to 3 years of working sense as a junior developer or five to vi years as a senior developer. It's fifty-fifty useful for freshers in addition to beginners to expand their knowledge. I volition add together novel in addition to latest multi-threading interrogation as in addition to when I come upwards across, in addition to I asking you lot all to ask, portion in addition to reply questions via comments to maintain this listing relevant to all Java programmers.


Further Learning
Multithreading in addition to Parallel Computing inwards Java
Applying Concurrency in addition to Multi-threading to Common Java Patterns
Java Concurrency inwards Practice Course past times Heinz Kabutz


Sumber https://javarevisited.blogspot.com/

0 Response to "Top L Coffee Thread Interview Questions Answers For Experienced"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel