- Explain about strategy pattern with code.
- write interface for strategy
2.implement strategy for two different strategies
3.write a context class to use strategy
- pass strategy into context class and call it
- Concurrent HashMap vs synchronized
1.You should use ConcurrentHashMap when you need very high concurrency in your project.
2.It is thread safe without synchronizing the whole map.
3.Reads can happen very fast while write is done with a lock.
4.There is no locking at the object level.
5.The locking is at a much finer granularity at a hashmap bucket level.
6.ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it.
7.ConcurrentHashMap uses multitude of locks.
1.Synchronization at Object level.
2.Every read/write operation needs to acquire lock.
3.Locking the entire collection is a performance overhead.
4.This essentially gives access to only one thread to the entire map & blocks all the other threads.
5.It may cause contention.
6.SynchronizedHashMap returns Iterator, which fails-fast on concurrent modification.
- what does mean by Threadsafe.
Ensures that particular task object would complete without interruption by other Thread. It helps to complete the Task.
- How do you start a Thread?
by start method(), run method()
- How do you handle concurrency?
“A class is threadsafe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or
interleaving of the execution of those threads by the runtime environment,and with noadditional synchronization or
other coordination on the part of the calling code.”
- Explain Singleton Pattern.
“allows only a single object to ever be created
1.double checking synchronized way: Lazy Loading
- statis final – Eager Loading
Java.lang.Runtime with getRuntime() method
Java.awt.Toolkit with getDefaultToolkit()
Java.awt.Desktop with getDesktop()
How to break singleton pattern?
- use different class loader
- use clone interface
- serialization – use readResolve to avoid
4.concurrent thread – use double locking ”
- Explain about collection in Java. How do you handle dublicates?
Set – TreeSet – No dublicate
List- ArrayList, LinkedList – Ordered way
Map – HashMap, TreeMap, HashTable, Dictionary, ZKey value pair
Collection c = new ArrayList() is better than List interface
HashMap – fast algorithem to retieve, no order
TreeMap – Keys sorted by ascending comparision order
LinkedHashMap- keeps the key in insertion order
ArrayList – excels randon access, slower insert or removing elements
LinkedList – good at insertion and deletions from the middle of a List
The concept of an Iterator (another design pattern) can be used to achieve this abstraction. An iterator is an object whose job is to move through a sequence and select each object in that sequence without the client programmer knowing or caring about the underlying structure of that sequence. works only on forward direction
ListIterator – works on both direction
LinkedList supports both queue and stack
- why concurrency?
Improve resource utilization/ Time Efficiency
Handle Blocking I/O easily
- hierachcal DB handle in core hava – write a program to handle in Memory
- flight schedule – Write Java program
- static vs instance
static – class level
– static method cannot be overridden
– executes only once
intance – object level
Hiding: Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it.
Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.
- annotation – how it works?
Annotation is code about the code, that is metadata about the program itself. In other words, organized data about the code, embedded within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too.
- add @Marker in interface where you wanted to make it as annotation 2. Add annototed interface at required places
Retention Policy to decide compile or runtime 3. write annotation processor ( uses reflection)
- What is mean by String is immutable?
StringPool- Special Storage area in heap, if the string created and if it already has variable, it will be returned.
Allow string to cache its hashcode – This helps in hashmap for storage object, string play as better key.
Security – many db, networking connections uses string as name. Changing would lead to security issues.The same case for Reflection.
Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues
Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).
- How can you make class as immutable?
- Why String is immutable?
- how to pass object from m/c to m/c? RMI, serialization
- Can we override static method?
No. we cannot.No, you cannot override static method in Java because method overriding is based upon dynamic binding at runtime and static methods are bonded using static binding at compile time. Though you can declare a method with same name and method signature in sub class which does look like you can override static method in Java but in reality that is method hiding.
- factory vs builder
both are creational pattern
Factory – provide single or family of related objects
builder – crafts complex different types of objects step by step, construction process helps to create different forms of objects.
- depth questions on multithreading code
- counter in core java
- Class Path issue –
Parent First, Parent Last, Depends on App Server
how do you solve class path issue?
- Explain about JVM and GC
Abstract computing m/c to run java program
HotSpot – ClassLoader with JRE
– Just In Compilation – dynamic translation, is
compilation done during execution of a program – at run time –
rather than prior to execution.
– Adaptieve Optimization – Dynamic compilation
Method Area(Shared among all threads(global), shared
class structures like field,method data,code for methods and
Runtime Constant Pool
Field & Method Area
Heap(Shared among all threads(global), stores all
created objects and arrays)
Eden – New/short-term objects are instantiated
in the eden space
From Survivor 0 -Survived/mid-term objects are
copied from the eden space to the survivor space.
From Survivor 1
Old Generation – Tenured/long-term objects are
copied from the survivor to the old generation space.
JVM Language Stacks
Native Method Stacks
Native Method Interface
Native Method Libraries
Thread 1..N( Private stack(local), Holds reference
to object in heap, stores local variables of primitive types)
***“In each thread stack the program is executed
referring to the Java logic in the method area and the object
data in the heap space”.****
How GC works?
– collection is performed frequently
– collection is focused more on speed efficiency.
— collection is performed less or in-frequently
– collection is focused more on time efficiency.
– very large
Most objects live for a short period.
Only few old objects have references to young objects.
- Serial – works by holding all application thread(freeze all
– designed for single threaded environtmnet
– doesn’t suitable for server, and suitable for
- Parallel – default GC
– halts application thread, but uses multiple thread
- mark live objects by start with root(thread stack, global
references and static variables)
2.In the sweep phase of the Mark-and-Sweep algorithm all
unreachable objects are declared as free memory.
- Uses more memory compared with Parallel.Better GC incase
of more CPU.
- CMC – avoids fragmentation by moving objects
- G1 – used for large heap memory areas
separate Heaps into region
- What are new feature and JDK 7 and are you aware about JDK 8 enhancements?
Java 5 Tiger
Generics – Provids compile type safety for collections
Enumerations – Typesafe
Enhanced for loops
improved memory model
Java 6 Mustang
Java compiler API
Java 7 Dolphin
Strings in switch
automatic resource managemnet in try-statement
date and time api
pipeline and streams
- “Have to build your own implementation of thread pool?
ExecutorService executor = Executors.newThreadPool(5);
Runnable worker = new WorkerThread(i);
- Did you sometime try to build your own web server in Java?”
- Give few examples where you wrote Abstract Base classes?
Abstact vs Interface
Abstract – provide IS A, this can be used when sub classes need
default functionality .If the base class is changed often abstarct class is the best approach.
Framework is the best place where we can use it for Abstarct class.
Interface – 1.Can do like this- used for common functionality need to be shared with unrelated classes. but different implementation.
Contains variable static final. Design By Contract.
Supports Runtime polymorphism.
Avoid hierarchical type framework frequent changes in interface break the implementation.Everything should be done at first
Composition vs Inheritence
Inheritance – compile time – IS A
Composition – Runtime
runtime – HAS A
- write own arraylist
two approaches. Simple class having most of them static methods and second java inheritance and polymorphism based.
- Draw process flow of JVM and explain each component?
- Draw and explain each functions of GC
- Explain thread locking
Intrinisic Lock: Every object in Java has Monitor, when synchronized key word applied, it locks the object. For static method, it applies on Class
Drawbacks of Intrinisic Locks:
- not possible to interrupt a thread waiting to acquire a lock(lock interruptly)
- not possible to attempt to acquire a lock without being willing to wait for it forever(try lock)
3.Cannot implement non-block-structured locking disciplines.
- DeadLock situations can occur.
Reentrant Lock – allows the thread to re-aquire the same lock multiple times.1)Polled and Timed Lock aquisitions, 2)Interruptable Lock aquisitions, 3)Non-block structure locking, 4)Fairness.
- What are the main steps you do when using JAXB?
XML, XMLSchema, POJO, JAXB
Marshalling – POJO to XML
UnMarshalling- XML to POJO
- What is WeakHashmap and why do we use it?
A weak reference, simply put, is a reference that isn’t strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector’s ability to determine reachability for you, so you don’t have to do it yourself.
Reference Queue – Keep track of Weak References.
Soft References – Same as weak, but it will stay in memory for sometime.
Phantom References – A phantom reference is one of the strengths or levels of ‘non strong’ reference defined in the Java programming language; the others being weak and soft. Phantom reference are the weakest level of reference in Java; in order from strongest to weakest, they are: strong, soft, weak, phantom.
An object is phantomly referenced after it has been finalized, but before its allocated memory has been reclaimed.s
- How do you decide Thread Pool Size?
- Number of processors
- Extra overhead for thread swicth
Formula 1 for simpler Tasks
Thread Pool Size = Number of processors +1
int poolSize = Runtime.getRuntime().availableProcessors() + 1;
Formula 2: Consider I/O or other blocking operations
N = Number of processor available in system.
U = Target utilization of CUP; 0 >= U <= 1.
W/C = Ration of wait and computation time.
Number of threads for thread pool can evaluate by this formula:
Number of Threads = N * U * (1 + W/C)
Formula 3: Amadhals Law
P – proportion of task excuted on parallel.N – number of processors
- “Threaddumb structure
- Why we need threaddump?”
healthy vs non-healthy(stuck)
Thread Life status
Why Threaddumb analysis?
appln and java concurrency problems
root cause of performamce problems
respose time contributors / performamce bottlenecks
impact of JVM pause on appln threads
- Diff b/w User Thread and Daemon Thread
Daemon thread exit when main thread exits.
User Thread continues after Main thread exits
- Explicit vs Intrinisc Lock
- What is volatile?
Declaring a volatile Java variable means: The value of this variable will never be cached thread-locally: all reads and writes will go straight to “main memory”; Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.
- Mutax vs Synchronizer block
it is called Mutex if only one person allow to watch the play
it is called Semaphore if N number of people allow to watch the play.If anybody leave the Theater during the play then other person can be allowed to watch play.
it is called CountDownLatch if no one allowed to enter until every person vacate the theater.Here each person has freewill to leave the theater. One or More Threads wait for other set of Threads to complete set of tasks.`
it is called Cyclicbarrier if theater will not start until every person enter in theater. Here showman can not start the show until all the person enter and grab the seat . Once the play finish same barrier will apply for next show
One or More thread in a group to complete certain set of tasks before start the next tasks.
Here , person is Thread , Play is resource.