Friday, July 24, 2015

Java Thread Interview Miscs



java.util.concurrent.ArrayBlockingQueue
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();

        notFull =  lock.newCondition();
    public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException {

        checkNotNull(e);
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length) {
                if (nanos <= 0)
                    return false;
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(e);
            return true;
        } finally {
            lock.unlock();
        }

    }

    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0) {
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            return dequeue();
        } finally {
            lock.unlock();
        }

    }


    public int size() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }

    }

    private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();

    }

    private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();
        return x;

    }

    public boolean remove(Object o) {
        if (o == null) return false;
        final Object[] items = this.items;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count > 0) {
                final int putIndex = this.putIndex;
                int i = takeIndex;
                do {
                    if (o.equals(items[i])) {
                        removeAt(i);
                        return true;
                    }
                    if (++i == items.length)
                        i = 0;
                } while (i != putIndex);
            }
            return false;
        } finally {
            lock.unlock();
        }

    }
    /**
     * Shared state for currently active iterators, or null if there
     * are known not to be any.  Allows queue operations to update
     * iterator state.
     */

    transient Itrs itrs = null;




Default priority for main thread is always 5, it can be changed later. Default priority for all other threads depends on the priority of parent thread.

Threads have their own stack
http://www.javamadesoeasy.com/2015/03/threads-implement-their-own-stack.html
class MyThread extends Thread{
   public void run(){
          System.out.println("in run() method");
   }
}

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
   public static void main(String...args){
          System.out.println("In main() method");
          method1();
   }
  
   static void method1(){
          MyThread obj=new MyThread();  
          obj.start();
   }
}
https://hellosmallworld123.wordpress.com/2014/07/26/java-multithread-interview-questions/
2) What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it?
The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. 
==> More...

Local Variable: Each thread will have its own stack and local variable is stored in the stack, so it is thread safe.
Local Object: Local Object’s reference is thread safe, however, the local object itself is not necessarily the same. As long as the reference is not shared between the threads, then it is thread safe. Otherwise, it is not.
Object Members: Are not thread safe, because it is stored in the shared heap.
To achieve thread safety:
1. use immutable objects: Although the immutable object itself is thread safe, its reference may be not.
2. Use synchronized block: all the synchronized block are synchronized on the object. If one of the synchronized block is being executed by one thread, the other thread must wait until the modification is done to enter a synchronized block on the same object.
public class ConcurrentHashMap {
    private final ReentrantReadWriteLock fLock = new ReentrantReadWriteLock();
    private final Lock readLock = fLock.readLock();
    private final Lock writeLock = fLock.writeLock();
    private final HashMap<String, String> dataMap = new HashMap<String, String>();
     
    public String get(String key) {
        String result = new String();
        readLock.lock();
        try {
            result = dataMap.get(key);
        }
        catch (Exception e) {
             
        }
        finally {
            readLock.unlock();
        }
        return result;
    }
     
    public void set(String key, String value) {
        writeLock.lock();
        try {
            dataMap.put(key, value);
        }
        catch (Exception e) {
             
        }
        finally {
            writeLock.unlock();
        }
    }
}

3)What are differences between wait and sleep method in java?
One major difference is wait release the lock or monitor while sleep doesn’t release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution

4) Write code to implement blocking queue in Java?
If he uses wait() and notify() method to implement blocking queue, Once interviewee successfully writes it you can ask him to write it again using new java 5 concurrent classes etc.
public class BlockingQueue {
    List<Integer> queue = new LinkedList<Integer>();
    int maxSize = 0;
    public BlockingQueue(int max) {
        maxSize = max;
    }
     
    public synchronized void  enqueue(int i) {
        while(queue.size() == maxSize) {// if trying to add to a full queue.
            wait();
        }
        if (queue.size() == 0) {// if adding to an empty queue, notify other waiting
            notifyAll();
        }
        queue.add(i);
    }
     
    public synchronized int dequeue() {
        while(queue.size() == 0) {// if trying to remove to an empty queue.
            wait();
        }
        if (queue.size() == maxSize) {// if removing from a full queue queue, notify other waiting threads
            notifyAll();
        }
        return queue.remove(0);
    }
}

5) Write code to solve the Produce consumer problem in Java?
I have shared one way to solve producer consumer problem using BlockingQueue in Java , so be prepare for surprises. Some time they even ask to implement solution of dining philosopher problem as well. Notice the use of take and put of LinkedBlockingQueue. compared to add and remove, put and take block the queue if the operation is not possible.
public class ProducerConsumer { //using blockingQueue
    private volatile BlockingQueue<Integer> sharedQ = new LinkedBlockingQueue<Integer>(); //shared blockingQueue, thread safe
    public ProducerConsumer(final int size)  {
        Thread p = new Thread(new Runnable(){ //producer thread
            @Override
            public void run() {
                for (int i = 0; i < size; i++) { // produce 10 integer
                        try {
                            System.out.println("Producing: " + i);
                            sharedQ.put(i);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                         
                }
            }
             
        });
         
        Thread c = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < size; i++) { // produce 10 integer
                    try {
                        System.out.println("Consuming: " + sharedQ.take());
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
             
        });
        c.start();
        p.start();
         
    }
    public static void main(String [] args) {
        ProducerConsumer pc = new ProducerConsumer(10);
    }67

6) Write a program which will result in deadlock? How will you fix deadlock in Java?
Just ask them you have n resources and n thread and to complete an operation you require all resources. Here n can be replace with 2 for simplest case and higher number to make question more intimidating. see How to avoid deadlock in java for more information on deadlock in Java.
==> transfer money between two accounts, A->B also B-A
public void method1(){
    synchronized(String.class){
        System.out.println("Aquired lock on String.class object");
        synchronized (Integer.class) {
            System.out.println("Aquired lock on Integer.class object");
        }
    }
}
public void method2(){
    synchronized(Integer.class){
        System.out.println("Aquired lock on Integer.class object");
        synchronized (String.class) {
            System.out.println("Aquired lock on String.class object");
        }
    }
}

4 conditions for dead lock. mutual exclusive, non-preemption, hold and wait, and circular wait. If you can break any of them, for example enforce an order of aquiring the resource, then the dead lock can be solved.

7) What is atomic operation? What are atomic operations in Java?
Simple java thread interview questions, another follow-up is do you need to synchronized an atomic operation? :)
Atomicity is a guarantee of isolation from concurrent processes. Additionally, atomic operations commonly have a succeed-or-fail definition — they either successfully change the state of the system, or have no apparent effect.
11) Why we call start() method which in turns calls run() method, why not we directly call run() method ?
when you call start() method it creates new Thread and execute code declared in run() while directly calling run() method doesn’t create any new thread and execute code on same calling thread. 
https://hellosmallworld123.wordpress.com/2014/05/21/threads-and-locks/
Difference between synchronized methods and synchronized block
Synchronized method: Methods of a class which need to be synchronized are declared with “synchronized” keyword. If one thread is executing a synchronized method, all other threads which want to execute any of the synchronized methods on the same objects get blocked.
Synchronized statement: It provides the synchronization for a group of statements rather than a method as a whole. It needs to provide the object on which these synchronized statements will be applied, unlike in a synchronized method. This is to make sure that the object will not be altered by other threads when executing the block by setting the monitor to the monitor of the object.

6. You are given a class with synchronized method A, and a normal method C. If you have two threads in one instance of a program, can they call A at the same time? Can they call A and C at the same time?
i) no, they can not. synchronized method can be run only from one thread.
ii) yes, if C is not protected, then it can be run by both thread at the same time.

http://segmentfault.com/a/1190000002638478
  • wait()来自于 java.lang.Object,任何对象都有此方法
  • sleep()来自于 java.lang.Thread,调用的对象为线程
看一下jdk的描述:
wait():Causes the current thread to wait until either another thread invokes the
java.lang.Object.notify() method or the java.lang.Object.notifyAll()method for this object, or a specified amount of time has elapsed.
使当前线程挂起,当对象调用java.lang.Object.notify()或者java.lang.Object.notifyAll()或者时间到期,则从wait()中恢复执行
sleep():Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
在指定的时间内使当前执行的线程睡眠(暂停执行)
wait()与sleep()最主要的区别就在于同步与锁,wiat()必须放在synchronized block中,否则会在program runtime时扔出java.lang.IllegalMonitorStateException异常。
  • wait()期间对象锁是释放的
  • 调用sleep()的时候锁并没有被释放,调用yield()也属于这种情况
    synchronized(LOCK) {   
        Thread.sleep(1000); // LOCK is held
    }
    
    synchronized(LOCK) {   
        LOCK.wait(); // LOCK is not held
    }
    
一般而言,wait()用于线程间的通信,sleep()用于线程状态的控制


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