Java Thread Interview Questions Part - 2 - BEHIND JAVA

Java Thread Interview Questions Part - 2

Share This

31. What is the difference between synchronized and ReentrantLock in Java?

ReentrantLock

On class level, ReentrantLock is a concrete implementation of Lock interface provided in Java concurrency package from Java 1.5 onwards. As per Javadoc, ReentrantLock is mutual exclusive lock, similar to implicit locking provided by synchronized keyword in Java, with extended feature like fairness, which can be used to provide lock to longest waiting thread. Lock is acquired by lock() method and held by Thread until a call to unlock() method. Fairness parameter is provided while creating instance of ReentrantLock in constructor. ReentrantLock provides same visibility and ordering guarantee, provided by implicitly locking, which means, unlock() happens before another thread get lock().

Difference between ReentrantLock and synchronized keyword

1) Another significant difference between ReentrantLock and synchronized keyword is fairness. synchronized keyword doesn't support fairness. Any thread can acquire lock once released, no preference can be specified, on the other hand you can make ReentrantLock fair by specifying fairness property, while creating instance of ReentrantLock. Fairness property provides lock to longest waiting thread, in case of contention.

2) Second difference between synchronized and Reentrant lock is tryLock() method. ReentrantLock provides convenient tryLock() method, which acquires lock only if its available or not held by any other thread. This reduce blocking of thread waiting for lock in Java application.

3) One more worth noting difference between ReentrantLock and synchronized keyword in Java is, ability to interrupt Thread while waiting for Lock. In case of synchronized keyword, a thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that. ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt thread when it is waiting for lock. Similarly tryLock() with timeout can be used to timeout if lock is not available in certain time period.

4) ReentrantLock also provides convenient method to get List of all threads waiting for lock.

Here is an example

32. There are three threads T1, T2, and T3? How do you ensure sequence T1, T2, T3 in Java?

Sequencing in multi-threading can be achieved by different means but you can simply use the join() method of thread class to start a thread when another one has finished its execution. To ensure three threads execute you need to start the last one first e.g. T3 and then call join methods in reverse order e.g. T3 calls T2. join and T2 calls T1.join, these ways T1 will finish first and T3 will finish last.

Here is an example of thread join

Important point on Thread.join method

Now we know How to use join method in Java, it’s time to see some important points about Thread.join() method.

  1. Join is a final method in java.lang.Thread class and you cannot override it.
  2. Join method throws IntrupptedException if another thread interrupted waiting for thread as a result of join() call.
  3. Join is also an overloaded method in Java, three version of join() available, check Javadoc for details.

33. What does yield method of Thread class do?

Yield method is one way to request current thread to relinquish CPU so that other thread can get a chance to execute. Yield is a static method and only guarantees that current thread will relinquish the CPU but doesn't say anything about which other thread will get CPU. Its possible for the same thread to get CPU back and start its execution again.

34. Compare yield and wait method?

Yield and wait method in Java, though both are related to Threads, are completely different to each other. 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.

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

2) The 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 static method and work on current thread.

4) Another difference on wait and yield is that When a Thread call waits 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 differentiates wait and yield is that, its advised to call wait method inside the loop but the yield is better to be called outside of the loop.

35. Is Swing thread-safe? What do you mean by Swing thread-safe?

No, Swing is not thread-safe. In one word, Since Swing is not thread-safe, you can not update Swing components from any random thread, they are always updated using Event Dispatcher thread

Since Swing is not thread-safe by design, it's designer did provide couple of utility methods in SwingUtilities class to update any Swing component from a thread other thread Event Dispatcher Thread. You can use invokeAndWait() and invokeLater() to update a Swing component from any arbitrary thread. As name suggest, invokeAndWait() is a synchronous, blocking method and blocks until GUI is updated, while invokeLater() is an asynchronous call and doesn't wait for GUI to be updated. By the way, both of these method make sure that Swing GUI components are updated in EDT thread only. Both of these method takes a Runnable object, which contains code to update GUI, as shown below :

SwingUtilities.invokeLater(new Runnable() {
  public void run() {
    JLable.setText("Update Title");
  }
}

36. When you use threads in Swing development, you risk of deadlock and frozen GUI. By following these simple rules, you minimize your chances of errors.

1) Since Swing components are not thread-safe, until any specifics mentioned in Javadoc, they must be created and modified from AWT Event Dispatcher thread.

2) Not only Swing components but also there model e.g. ListModel, TableModel must be modified from Event Dispatcher thread.

3) AWT Event Dispatcher thread is responsible for updating GUI and listening events, so don't block them by doing time consuming task there.

4) You can use java.awt.EventQueue's isDispatchThread() or SwingUtilities.isEventDispatchThread() to check if current thread is EDT.

5) Use SwingWorker to perform lengthy time consuming task in worker thread

.

6) Use InvokeAndWait() and invokeLater() to update GUI components from threads other than Event Dispatcher thread.

37. How to create an Immutable object in Java?

Immutable classes are those class, whose object can not be modified once created, it means any modification on immutable object will result in another immutable object. best example to understand immutable and mutable objects are, String and StringBuffer. Since String is immutable class, any change on existing string object will result in another string e.g. replacing a character into String, creating substring from String, all result in a new objects. While in case of mutable object like StringBuffer, any modification is done on object itself and no new objects are created. Some times this immutability of String can also cause security hole, and that the reason why password should be stored on char array instead of String.

Here follows the steps to creating Immutable object

  1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
  2. All fields of Immutable class should be final.
  3. Object must be properly constructed i.e. object reference must not leak during construction process.
  4. Object should be final in order to restrict sub-class for altering immutability of parent class.

38. Why character array is better than String for Storing password in Java?

1) Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text and that's another reason you should always used an encrypted password than plain text. Since Strings are immutable there is no way contents of Strings can be changed because any change will produce new String, while if you char[] you can still set all his element as blank or zero. So Storing password in character array clearly mitigates security risk of stealing password.

2) Java itself recommends using getPassword() method of JPasswordField which returns a char[] and deprecated getText() method which returns password in clear text stating security reason. Its good to follow advice from Java team and adhering to standard rather than going against it.

3) With String there is always a risk of printing plain text in log file or console but if use Array you won't print contents of array instead its memory location get printed. though not a real reason but still make sense.

String strPassword="Unknown";
char[] charPassword= new char[]{'U','n','k','w','o','n'};
System.out.println("String password: " + strPassword);
System.out.println("Character password: " + charPassword);

String password: Unknown
Character password: [C@110b053

39. What is busy spin in multi-threading?

Busy spin is a technique which concurrent programmers employ to make a thread wait on certain condition. Unlike traditional methods e.g. wait(), sleep() or yield() which all involves relinquishing CPU control, this method does not relinquish CPU, instead it the just runs empty loop. Why would someone do that? to preserve CPU caches. In a multi-core system, it's possible for a paused thread to resume on a different core, which means rebuilding cache again. To avoid cost of rebuilding cache, programmer prefer to wait for much smaller time doing busy spin

40. What happens if a thread throws an Exception inside synchronized block?

no matter how you exist synchronized block, either normally by finishing execution or abruptly by throwing exception, thread releases the lock it acquired while entering that synchronized block. This is actually one of the reasons I like synchronized block over lock interface, which requires explicit attention to release lock, generally this is achieved by releasing the lock in a finally block.

41. What is the fork-join framework in Java?

The fork-join framework, introduced in JDK 7 is a powerful tool available to Java developer to take advantage of multiple processors of modern day servers. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application. One significant advantage of The fork/join framework is that it uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy.

No comments:

Post a Comment

Pages