Sunday, July 5, 2015

Java Thread Interview Question from Java67



http://javarevisited.blogspot.com/2016/04/difference-between-ExecutorServie-submit-vs-Executor-execute-method-in-Java.html
A main difference between the submit() and execute() method is that ExecuterService.submit()can return result of computation because it has a return type of Future, but execute() method cannot return anything because it's return type is void

The core interface in Java 1.5's Executor framework is the Executor interface which defines the execute(Runnable task) method, whose primary purpose is to separate the task from its execution.

Any task submitted to Executor can be executed by the same thread, a worker thread from a thread pool or any other thread.

On the other hand, submit() method is defined in the ExecutorService interface which is a sub-interface of Executor and adds the functionality of terminating the thread pool, along with adding submit() method which can accept a Callable task and return a result of computation.
Apart from the fact that submit() method can return output and execute() cannot, following are other notable differences between these two key methods of Executor framework of Java 5.

1) The submit() can accept both Runnable and Callable task but execute() can only accept the Runnable task.

2) The submit() method is declared in ExecutorService interface while execute() method is declared in the Executor interface.

3) The return type of submit() method is a Future object but return type of execute() method is void.


Difference between yield and wait method in Java?
Main difference between wait and yield in Java is that wait() is used for flow control and inter thread communication while yield is used just to relinquish CPU to offer an opportunity to another thread for running.
In summary wait and yield are completely different and there for different purpose. 
Use wait for inter thread communication while yield is not just reliable enough even for the mentioned task. prefer Thread.sleep(1) instead of yield.
yield implementation is platform dependent, and not reliable.

Difference between wait and yield in Java
1) First difference between wait vs yield method is that, wait() is declared in java.lang.Object class while Yield is declared onjava.lang.Thread class.

2) Second difference between wait and yield in Java is that wait is overloaded method and has two version of wait, normal and timed wait while yield is not overloaded.

3) Third difference between wait and yield is that wait is an instance method while yield is an staticmethod and work on current thread.

4) Another difference on wait and yield is that When a Thread call wait it releases the monitor.

5) Fifth difference between yield vs wait which is quite important as well is that wait() method must be called from either synchronized block or synchronized method, There is no such requirement for Yield method.

6) Another Java best practice which differentiate wait and yield is that, its advised to call wait method inside loop but yield is better to be called outside of loop.

Difference between yield and sleep in Java?
Sleep and yield are two methods which is used to get CPU back from Thread to Thread Scheduler in java but they are completely different than each other. Major difference between Sleep vs yield is that sleep is more reliable than yield and its advised to use sleep(1) instead of yield to relinquish CPU in multi-threaded Java application to give an opportunity to other threads to execute. 
Similarities between Sleep and yield in Java:
1) Both yield and sleep are declared on java.lang.Thread class.

2) Both sleep() and yield() are static methods and operate on current thread. It doesn't matter which thread's object you used to call this method, both these methods will always operate on current thread.

3) Sleep as well as Yield is used to relinquish CPU from current thread, but at same time it doesn't release any lock held by the thread. If you also want to release locks along with releasing CPU, you should be using wait() method instead.
Difference between sleep and yield in Java
1) Thread.sleep() will cause currently executing thread to stop execution and relinquish the CPU to allow Thread scheduler ot allocate CPU to another thread or same thread depends upon Thread scheduler.Thread.yield() also used to relinquish CPU but behavior of sleep() is more determined than yield across platform. Thread.sleep(1) is better option than calling Thread.yield for same purpose.

2) Thread.sleep() method doesn't cause currently executing thread to give up any monitors while sleeping.

3) Thread.sleep() method throws InterruptedExcepiton if another thread interrupt the sleeping thread, this is not the case with yiedl method.

Difference between notify and notifyAll in Java?
wait, notify, and notifyAll methods are used for inter thread communication in Java. wait() allows a thread to check for a condition, and wait if condition doesn't met, while notify() and notifyAll()method informs waiting thread for rechecking condition, after changing state of shared variable. 

1. First and main difference between notify() and notifyAll() method is that, if multiple thread is waiting on any lock in Java, notify send notification to only one of waiting thread while notifyAllinforms all threads waiting on that lock.

2. If you use notify method , It's not guaranteed that, which thread will be informed, but if you usenotifyAll, since all thread will be notified, they will compete for lock and the lucky thread which gets lock will continue. In a way notifyAll method is more safe because it send notification to all threads, so if any thread misses the notification, there are other threads to do the job, while in case of notify method if the notified thread misses the notification then it could create subtle, hard to debug issues. 

Prefer notifyAll over notify whenever in doubt and if you can.
Avoid using notify and notifyAll altogether, instead use concurrency utility likeCountDownLatchCyclicBarrier, and Semaphore to write your concurrency code. It's not easy to get wait and notify method working correct in first attempt and concurrency bugs are often hard to figure out.

Top 12 Java Thread, Concurrency and Multithreading Interview Questions and How to Answers them
1) What is difference between start and run method in Java Thread?
because start method creates a new thread and call the code written inside run method on new thread while calling run method executes that code on same thread.
2) Write code to avoid deadlock in Java where n threads are accessing n shared resources?
The order of acquiring and release resource.
How to prevent deadlock in Java
3) Which one is better to implement thread in Java ? extending Thread class or implementing Runnable?
multiple inheritance at class level and separation of defining a task and execution of task. Runnable only represent a task, while Thread represent both task and it's execution.
4) What is Busy Spinning? Why you will use Busy Spinning as wait strategy?
It's a wait strategy, where one thread wait for a condition to become true, but instead of calling wait or sleep method and releasing CPU, it just spin. This is particularly useful if condition is going to be true quite quickly i.e. in millisecond or micro second. Advantage of not releasing CPU is that, all cached data and instruction are remained unaffected, which may be lost, had this thread is suspended on one core and brought back to another thread.

5) What is difference between CountDownLatch and CyclicBarrier in Java?
Both are used to implement scenario, where one thread has to wait for other thread before starting processing but there is difference between them. 
CountDownLatch is not reusable once count reaches to zero, while CyclicBarrier can be reused even after barrier is broken.

9) What is difference between submit() and execute() method of Executor and ExecutorService in Java?
Main difference between submit and execute method from ExecutorService interface is that former return a result in form of Future object, while later doesn't return result. By the way both are used to submit task to thread pool in Java but one is defined in Executor interface,while other is added intoExecutorService interface.
12) What is ReadWriteLock in Java? What is benefit of using ReadWriteLock in Java?
ReadWriteLock is again based upon lock striping by providing separate lock for reading and writing operations. If you have noticed before, reading operation can be done without locking if there is no writer and that can hugely improve performance of any application. ReadWriteLock leverage this idea and provide policies to allow maximum concurrency level.
you can even expect to provide your own implementation of ReadWriteLock, so be prepare for that as well.
public class ReentrantReadWriteLock
        implements ReadWriteLock, java.io.Serializable {
    private static final long serialVersionUID = -6992448646407690164L;
    /** Inner class providing readlock */
    private final ReentrantReadWriteLock.ReadLock readerLock;
    /** Inner class providing writelock */
    private final ReentrantReadWriteLock.WriteLock writerLock;
    /** Performs all synchronization mechanics */

    final Sync sync;
    public ReentrantReadWriteLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
        readerLock = new ReadLock(this);
        writerLock = new WriteLock(this);
    }

    public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }

    public ReentrantReadWriteLock.ReadLock  readLock()  { return readerLock; }
}
What is volatile variable in Java - When to use | Java67

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts