Thursday, 31 October 2013
Saturday, 12 October 2013
Thursday, 10 October 2013
Tuesday, 8 October 2013
Thursday, 19 September 2013
Inter-thread communication using wait notify scenario
Question - There are three threads,t1, t2 and t3, each of these thread have an array of size three. thread t1 has array {1,4,7}, thread t2 has array {2,5,8}, thread t3 has array {3,6,9}.
How to design the thread execution so that the output of execution will be 1,2,3,4,5,6,7,8,9
Solution - It is an scenario of multi-thread communication being handled using wait & notify methods.
The code is as mentioned below -
While testing in quad core processor machine, we found it working fine. But this solution might get into dead lock situation if first signal from main to first thread gets missed.
We could mitigate this problem, by using semaphore. The solution code is as mentioned below -
As in this problem, at a moment of time, only one thread should be in action to give the result in a specific sequence. We can implement the solution using Exchanger as well. The implementation is as mentioned below -
The problem can be solved easily without using any synchronized construct, and implementing threads using callable construct. The complete working code is as following -
The same problem can be solved using wait notify mechanism by designing SequenceLatch. The solution is as mentioned following -
How to design the thread execution so that the output of execution will be 1,2,3,4,5,6,7,8,9
Solution - It is an scenario of multi-thread communication being handled using wait & notify methods.
The code is as mentioned below -
public class InterThreadCommunication {
static class SampleRunnable implements Runnable
{
final int[] arrayToPrint;
final Object waitMonitor;
final Object notifyMonitor;
public SampleRunnable(int[] arrayToPrint, Object waitMonitor, Object notifyMonitor) {
this.waitMonitor = waitMonitor;
this.notifyMonitor = notifyMonitor;
this.arrayToPrint = arrayToPrint;
}
@Override
public void run() {
try {
setCurrentMonitorToWait();
System.out.println(arrayToPrint[0]);
notifyNextMonitor();
setCurrentMonitorToWait();
System.out.println(arrayToPrint[1]);
notifyNextMonitor();
setCurrentMonitorToWait();
System.out.println(arrayToPrint[2]);
notifyNextMonitor();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void setCurrentMonitorToWait() throws InterruptedException {
synchronized (waitMonitor) {
this.waitMonitor.wait();
}
}
private void notifyNextMonitor() {
synchronized (notifyMonitor) {
this.notifyMonitor.notify();
}
}
}
public static void main(String[] args) {
Object firstMonitor = new Object();
Object secondMonitor = new Object();
Object thirdMonitor = new Object();
int[] a1 = new int[] {1,4,7};
int[] a2 = new int[]{2,5,8};
int[] a3 = new int[]{3,6,9};
Thread t1 = new Thread(new InterThreadCommunication.SampleRunnable(a1,firstMonitor,secondMonitor));
Thread t2 = new Thread(new InterThreadCommunication.SampleRunnable(a2, secondMonitor, thirdMonitor));
Thread t3 = new Thread(new InterThreadCommunication.SampleRunnable(a3, thirdMonitor, firstMonitor));
t1.start();
t2.start();
t3.start();
synchronized (firstMonitor) {
firstMonitor.notify();
}
}
}
While testing in quad core processor machine, we found it working fine. But this solution might get into dead lock situation if first signal from main to first thread gets missed.
We could mitigate this problem, by using semaphore. The solution code is as mentioned below -
import java.util.concurrent.Semaphore;
public class InterThreadCommunication {
static class SampleRunnable implements Runnable
{
final int[] arrayToPrint;
final Semaphore acquireSemaphore;
final Semaphore releaseSemaphore;
public SampleRunnable(int[] arrayToPrint, Semaphore acquireSemaphore, Semaphore releaseSemaphore) {
this.acquireSemaphore = acquireSemaphore;
this.releaseSemaphore = releaseSemaphore;
this.arrayToPrint = arrayToPrint;
}
@Override
public void run()
{
try {
this.acquireSemaphore.acquire();
System.out.println(arrayToPrint[0]);
this.releaseSemaphore.release();
this.acquireSemaphore.acquire();
System.out.println(arrayToPrint[1]);
this.releaseSemaphore.release();
this.acquireSemaphore.acquire();
System.out.println(arrayToPrint[2]);
this.releaseSemaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Semaphore firstSemaphore = new Semaphore(0);
Semaphore secondSemaphore = new Semaphore(0);
Semaphore thirdSemaphore = new Semaphore(0);
int[] a1 = new int[] {1,4,7};
int[] a2 = new int[]{2,5,8};
int[] a3 = new int[]{3,6,9};
Thread t1 = new Thread(new InterThreadCommunication.SampleRunnable(a1,firstSemaphore,secondSemaphore));
Thread t2 = new Thread(new InterThreadCommunication.SampleRunnable(a2, secondSemaphore, thirdSemaphore));
Thread t3 = new Thread(new InterThreadCommunication.SampleRunnable(a3, thirdSemaphore, firstSemaphore));
t1.start();
t2.start();
t3.start();
firstSemaphore.release();
}
}
As in this problem, at a moment of time, only one thread should be in action to give the result in a specific sequence. We can implement the solution using Exchanger as well. The implementation is as mentioned below -
import java.util.concurrent.Exchanger;
public class PipeLineOperation extends Thread {
private int threadNumber;
private Exchanger firstExchanger;
private Exchanger secondExchanger;
private int[] firstArray;
private int[] secondArray;
private int[] currentArray;
public PipeLineOperation(int threadNumber, Exchanger firstExchanger, Exchanger secondExchanger, int[] threadsArray) {
this.firstExchanger = firstExchanger;
this.secondExchanger= secondExchanger;
this.threadNumber = threadNumber;
this.currentArray = threadsArray;
}
@Override
public void run()
{
try
{
performOperationInthread();
}
catch(InterruptedException interruptedException)
{
throw new RuntimeException(interruptedException);
}
}
private void performOperationInthread() throws InterruptedException {
if(threadNumber == 0)
{
firstArray = currentArray;
secondArray = firstExchanger.exchange(currentArray);
currentArray = secondExchanger.exchange(currentArray);
for (int i = 0; i < 3; i++) {
System.out.println(firstArray[i]);
System.out.println(secondArray[i]);
System.out.println(currentArray[i]);
}
}
else
{
currentArray = firstExchanger.exchange(currentArray);
}
}
public static void main(String[] args) {
Exchanger firstExchanger= new Exchanger<>();
Exchanger secondExchanger = new Exchanger<>();
new PipeLineOperation(0, firstExchanger, secondExchanger, new int[] {1,4,7}).start();
new PipeLineOperation(1, firstExchanger, null, new int[]{2,5,8}).start();
new PipeLineOperation(2, secondExchanger, null, new int[]{3,6,9}).start();
}
}
The problem can be solved easily without using any synchronized construct, and implementing threads using callable construct. The complete working code is as following -
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class PipeLineOperation implements Callable {
private final int[] holdingArray;
public PipeLineOperation(final int[] holdingArray) {
this.holdingArray=holdingArray;
}
@Override
public int[] call() throws Exception {
return holdingArray;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
final ExecutorService executorService = Executors.newFixedThreadPool(3);
final FutureTask firstFutureTask = (FutureTask) executorService.submit(new PipeLineOperation(new int[]{1,4,7}));
final FutureTask secondFutureTask = (FutureTask) executorService.submit(new PipeLineOperation(new int[]{2,5,8}));
final FutureTask thirdFutureTask = (FutureTask) executorService.submit(new PipeLineOperation(new int[]{3,6,9}));
executorService.shutdown();
final int[] firstArray = firstFutureTask.get();
final int[] secondArray = secondFutureTask.get();
final int[] thirdArray = thirdFutureTask.get();
for (int i = 0; i < 3; i++) {
System.out.println(firstArray[i]);
System.out.println(secondArray[i]);
System.out.println(thirdArray[i]);
}
}
}
The same problem can be solved using wait notify mechanism by designing SequenceLatch. The solution is as mentioned following -
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SequencialLatchDemo {
public static void main(String[] args) throws InterruptedException {
SequencialLatch firstLatch = new SequencialLatch();
SequencialLatch secondLatch = new SequencialLatch();
SequencialLatch thirdLatch = new SequencialLatch();
firstLatch.setNext(secondLatch);
secondLatch.setNext(thirdLatch);
thirdLatch.setNext(firstLatch);
Runner runner1 = new Runner(new int[] { 1, 4, 7 }, 1, firstLatch);
Runner runner2 = new Runner(new int[] { 2, 5, 8 }, 2, secondLatch);
Runner runner3 = new Runner(new int[] { 3, 6, 9 }, 3, thirdLatch);
ExecutorService service = Executors.newFixedThreadPool(3);
service.submit(runner2);
service.submit(runner3);
service.submit(runner1);
service.shutdown();
}
}
class Runner implements Runnable {
private final SequencialLatch pass;
private final int[] numbers;
private final int threadNumber;
public Runner(int[] numbers, final int threadNumber, SequencialLatch pass) {
this.numbers = numbers;
this.pass = pass;
this.threadNumber = threadNumber;
}
@Override
public void run() {
for (int taskNumber = 0; taskNumber < numbers.length; taskNumber++) {
if (!(this.threadNumber == 1 && taskNumber == 0))
pass.await();
System.out.println(numbers[taskNumber]);
pass.nextPerssionRelease();
}
}
}
class SequencialLatch {
private SequencialLatch next;
private boolean active;
public void nextPerssionRelease() {
this.active = false;
next.active = true;
synchronized (next) {
next.notify();
}
}
public void await() {
while (!active) {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void setNext(SequencialLatch existingPass) {
this.next = existingPass;
}
}
The same problem can be solved using Lock and Condistion mechanism by designing SequenceLatch. The solution is as mentioned following -
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SequencialLatchDemo {
public static void main(String... args) throws InterruptedException {
SequencialLatch firstLatch = new SequencialLatch();
SequencialLatch secondLatch = new SequencialLatch();
SequencialLatch thirdLatch = new SequencialLatch();
firstLatch.setNext(secondLatch);
secondLatch.setNext(thirdLatch);
thirdLatch.setNext(firstLatch);
Runner runner1 = new Runner(new int[] { 1, 4, 7 }, 1, firstLatch);
Runner runner2 = new Runner(new int[] { 2, 5, 8 }, 2, secondLatch);
Runner runner3 = new Runner(new int[] { 3, 6, 9 }, 3, thirdLatch);
ExecutorService service = Executors.newFixedThreadPool(3);
service.submit(runner2);
service.submit(runner3);
service.submit(runner1);
service.shutdown();
}
}
class Runner implements Runnable {
private final SequencialLatch pass;
private final int[] numbers;
private final int threadNumber;
public Runner(int[] numbers, final int threadNumber, SequencialLatch pass) {
this.numbers = numbers;
this.pass = pass;
this.threadNumber = threadNumber;
}
@Override
public void run() {
for (int taskNumber = 0; taskNumber < numbers.length; taskNumber++) {
if (!(this.threadNumber == 1 && taskNumber == 0))
pass.await();
System.out.println(numbers[taskNumber]);
pass.nextPerssionRelease();
}
}
}
class SequencialLatch {
private final static Lock baseLock = new ReentrantLock();
private final Condition condition = baseLock.newCondition();
private boolean active;
private SequencialLatch next;
public void nextPerssionRelease() {
baseLock.lock();
try {
this.active = false;
next.active = true;
next.condition.signal();
} finally {
baseLock.unlock();
}
}
public void await() {
baseLock.lock();
try {
while (!active) {
condition.await();
}
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
} finally {
baseLock.unlock();
}
}
public void setNext(SequencialLatch existingPass) {
this.next = existingPass;
}
}
Wednesday, 18 September 2013
Max number existing in any of the participating table columns
Question - There are two tables (Ex - test1 & test2 ) having only one column of number type (Ex. number1 & number2). Write a query to find out max number existing in any of these tables.
Sample data setup query -
Three possible solutions -
Sample data setup query -
CREATE TABLE test1( number1 NUMBER);
insert into test1 values (21);
INSERT INTO test1 VALUES (22);
INSERT INTO test1 VALUES (23);
INSERT INTO test1 VALUES (24);
insert into test1 values (25);
CREATE TABLE test2( number2 NUMBER);
INSERT INTO test2 VALUES (211);
INSERT INTO test2 VALUES (221);
INSERT INTO test2 VALUES (231);
INSERT INTO test2 VALUES (241);
insert into test2 values (251);
Three possible solutions -
SELECT greatest((SELECT MAX(number1) FROM test1), (SELECT MAX(number2) FROM test2)) MAX FROM dual;
SELECT CASE WHEN (MAX(number1)>MAX(number2))
THEN MAX(number1)
ELSE
MAX(number2)
END CASE
from test1,test2;
SELECT MAX(number3) FROM
(
(SELECT MAX(number1)number3 FROM test1)
UNION
(SELECT MAX(number2)number3 FROM test2)
);
Thursday, 5 September 2013
Tuesday, 3 September 2013
Multithreading Concepts
- Thread-local, when & how to use it
- Thread local API
- Interrupting other threads
- Reasons to use multithreading
- Concurrency tutorial
- CyclicBarrier way of working
- Creating thread pool using java executor framework
- Thread pool executor - http://tutorials.jenkov.com/java-util-concurrent/executorservice.html
- Starvation and livelock
- Fork and join working and improvement from previous way
- How to use ConcurrentHashMap
- Java memory model in multithreading
- Memory barriers and JVM concurrency
Thursday, 22 August 2013
Monday, 19 August 2013
Friday, 15 March 2013
Security Interview Questions
- Top ten web attacks -
- Cross site attack
- Preventing cross site attack
- Network layer
- What is SSL Certificate
- SSL Frequently asked questions
- Tomcat SSL configuration
- SSL Handshake
- Securing web application using SSL
- Java application using SSL
- Key Tool, Creating Self Signed Certificate
- Understanding SSL handshake
Sunday, 27 January 2013
Design related interview questions
- Object oriented design principles
- Software design interview questions
- When to use interface
- Java enum is class or interface
- Java67 design pattern questions and answers
- Java revisited programming interview questions
- How to analyze the thread dump
- Understanding various design patterns
- UML class diagram understanding & creation
- Points to consider while implementing Observer design pattern
- Difference between dependency injection and dependency lookup
- How to program multithreading communication
- Managing code maintainability
- Maintaining code robustness
- Implementing extensible code
- Optimistic concurrency control concept
- Optimistic vs Pessimistic locking in Hibernate
- What is time complexity
- What is big O notation
- How to calculate the complexity of algorithm
- Sorting Algorithms -
- Searching Algorithms -
Wednesday, 23 January 2013
Spring-Core interview questions
Implementation Based -
Auto wiring -
http://www.coderanch.com/t/603029/Spring/Autowired-properies
Common Questions - http://javarevisited.blogspot.in/2011/09/spring-interview-questions-answers-j2ee.html
Fundamental -
http://java67.blogspot.sg/2012/08/spring-interview-questions-answers.html
- Can we assign the reference of prototype bean to singleton bean & vise versa ?
- Is spring singleton , singleton to class-loader or not ?
- Difference in life cycle of singleton and prototype bean ? (hint - destroy-method execution)
- Spring annotations and their purpose
- Difference between <context:annotation-config> and <context:component-scan>
- Register singleton bean to spring factory using registerSingleton
Tuesday, 22 January 2013
Core java fundamental interview questions
- In the non-static method, the reference to the instance of the enclosing context is passed implicitly in the constructor call of the non-static local class
- Equals , comparable and comparator - http://leepoint.net/notes-java/data/expressions/22compareobjects.html
- Common Question - http://bateru.com/news/2011/
03/484/ - Common question - http://www.fromdev.com/2010/08/10-jdbc-questions-for-java-beginners.html
- Good questions - http://javarevisited.blogspot.in/2011/04/top-20-core-java-interview-questions.html
- Multithreading - http://www.fromdev.com/2008/05/java-threading-questions.html
- Collection - http://www.fromdev.com/2008/05/java-collections-questions.html
- Classpath - http://www.fromdev.com/2012/09/Java-Path-Classpath-Questions-Answers.html
- Jdbc - http://www.fromdev.com/2010/08/10-jdbc-questions-for-java-beginners.html
- Why static method override is not allowed
- Starting thread more than once - http://stackoverflow.com/questions/1215548/is-it-legal-to-call-the-start-method-twice-on-the-same-thread
- Wait notify- notify all - http://javarevisited.blogspot.sg/2011/05/wait-notify-and-notifyall-in-java.html
- Volatile vs synchronization - http://javarevisited.blogspot.in/2011/06/volatile-keyword-java-example-tutorial.html
- HashTable vs Concurrent HashMap vs SyncronizedMap - http://javarevisited.blogspot.sg/2011/04/difference-between-concurrenthashmap.html
- HashSet Vs TreeSet -http://java67.blogspot.sg/2012/08/difference-between-hashset-and-treeset-java.html
- http://javarevisited.blogspot.sg/2011/08/what-is-polymorphism-in-java-example.html
- http://java67.blogspot.sg/2012/08/difference-between-string-and-stringbuffer-in-java.html
- http://javarevisited.blogspot.sg/2012/01/how-to-reverse-string-in-java-using.html
- http://java67.blogspot.sg/2012/09/java-collection-interview-questions.html
- http://java67.blogspot.sg/2012/09/what-is-new-in-java-7-top-5-jdk-7.html
- http://java67.blogspot.sg/2012/08/10-java-coding-interview-questions-and.html
- http://java67.blogspot.sg/2012/08/5-thread-interview-questions-answers-in.html
- http://java67.blogspot.sg/2012/09/top-10-tough-core-java-interview-questions-answers.html
- http://javarevisited.blogspot.in/2011/11/collection-interview-questions-answers.html
- http://javarevisited.blogspot.in/2011/02/how-hashmap-works-in-java.html
- http://javarevisited.blogspot.in/2011/04/top-20-core-java-interview-questions.html
- http://javarevisited.blogspot.in/2012/12/difference-between-equals-method-and-equality-operator-java.html
- http://javarevisited.blogspot.sg/2011/04/difference-between-concurrenthashmap.html
- http://java67.blogspot.in/2012/09/java-collection-interview-questions.html
Other important questions -
- What are advantages and disadvantages of singleton
- Fail safe and fail fast iterator & internal working on fail fast iterator
- The way to synchronize hash map-
- By passing it to the constructor of HashMap
- By passing it to the constructor of HashTable
- By calling synchronizedMap method of collections class
- By providing custom synchronized implementation
- ClassNotFoundException Vs NoClassDefFoundError
- What is stackOverFlow Error and can it be caught
- New features in Java7
- Caching on wrapper classes
Serialization interview questions -
Monday, 21 January 2013
TDD implementation based interview questions
code structure while using mock -
http://www.coderanch.com/t/603031/Testing/mock-return-method
Other important concepts -
http://www.coderanch.com/t/603031/Testing/mock-return-method
Other important concepts -
Sunday, 20 January 2013
Hibernate fundamental interview questions
Query cache vs second level cache -
http://www.coderanch.com/t/602070/ORM/databases/Query-Level-Cache
http://www.javalobby.org/java/forums/t48846.html
http://www.coderanch.com/t/526101/ORM/databases/Relation-Hibernate-Query-Cache-Level
Foreign key relationship managing (inverse)-
http://www.coderanch.com/t/479189/ORM/databases/inverse-hibernate
http://www.coderanch.com/t/218391/ORM/databases/Inverse
Other useful information -
http://www.coderanch.com/t/602070/ORM/databases/Query-Level-Cache
http://www.javalobby.org/java/forums/t48846.html
http://www.coderanch.com/t/526101/ORM/databases/Relation-Hibernate-Query-Cache-Level
Foreign key relationship managing (inverse)-
http://www.coderanch.com/t/479189/ORM/databases/inverse-hibernate
http://www.coderanch.com/t/218391/ORM/databases/Inverse
Other useful information -
- What is inverse
- Cascade in Hibernate
- Hibernate fetching strategy change at run-time
- Hibernate query generation mechanism selection
- Hibernate inheritance mapping strategy concept
- Hibernate inheritance mapping strategy code
- Hibernate implicit inheritance mapping
- Hibernate collection and it's usage
- Hibernate session flushing
- Hibernate flushing strategy
- Hibernate commit vs flush
- Drawbacks of second level cache
- Hibernate filters and their usage
- Issues with primitive type mapping in Hibernate
- Fetching strategy and their impact in sql query generation
- Mapping java enum to database column
Database interview questions
- Trigger types
- Transaction handling in oracle pl/sql
- Clustered and Non-Clustered index
- SQL Query related interview question
- Oracle general interview question - 1
- Oracle general interview question - 2
- Max number existing in any of the tables
- Identifying left outer and right outer join
- Difference between DBA and SYSDBA
- What is table partitioning and when it should be done
- Queries for table partitioning
- Partitioning existing table using exchange partition
- Partitioning existing table using dbms_redifinition
- Getting table partition related information using all_tab_partition
- SQL interview question series
Analytic Interview Questions -
- Handling table's heirarchical data in query
- Analytical function query
- Analytical function based query
Core Java implementation based questions
Race Condition scenarios-
Other good questions & Scenarios -
- i++ not being an atomic operation
- Join causes only the calling thread to wait for operation completion not to another thread calling join method on the same parent thread
Other good questions & Scenarios -
- Develop a horse racing program
- Scenario of identifying right monitor in thread and importance of Yield method
- Controlling the sequence of execution in multithread scenario using wait-notify
- Javarevisited multithreading interview questions
- Dead lock Scenario in Money transfer module
Spring-orm implementation based question
Designing -
http://www.coderanch.com/t/602653/ORM/databases/dynamicall-decide-database-referred
Q- How to perform operations in transaction while using HibernateTemplate or JDBCTemplate?
Ans- a) transaction across multiple JDBCTemplate or HibernateTemplate
b) Declarative (aop or annotation base) & programmatic transaction management configuration
Q- Possible isolation levels & propagation of a transaction and way to use it in Spring -
http://en.wikipedia.org/wiki/Isolation_%28database_systems%29
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations
http://static.springsource.org/spring/docs/1.2.9/api/org/springframework/transaction/annotation/Isolation.html
http://www.coderanch.com/t/
Q- How to perform operations in transaction while using HibernateTemplate or JDBCTemplate?
Ans- a) transaction across multiple JDBCTemplate or HibernateTemplate
b) Declarative (aop or annotation base) & programmatic transaction management configuration
Q- Possible isolation levels & propagation of a transaction and way to use it in Spring -
http://en.wikipedia.org/wiki/Isolation_%28database_systems%29
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations
http://static.springsource.org/spring/docs/1.2.9/api/org/springframework/transaction/annotation/Isolation.html
Ques-Spring's @Transactional on class level applies to what methods?
Ans-http://stackoverflow.com/questions/28170851/springs-transactional-on-class-level-applies-to-what-methods#
Hibernate implementation based interview questions
- Cascade and lack on inverse causing duplicate in many to many
- Implicit inverse in one to many relationship
- Implementing optimistic locking in Hibernate
- Optimistic and pessimistic locking implementation in Hibernate
- Using c3p0 connection pool in Hibernate
- Using projection and distinct in detached Criteria query
Subscribe to:
Posts (Atom)