Continue on the technical part of the interview. Some of Java memory management, thread, concurrency and exception questions are answered below.
How Java does memory management work?
Memory in Java is mainly divided into two areas: stack and heap memory.
Stack(LIFO (Last In, First Out)) memory is used to store local variables and function call.While heap memory is used to store objects. Java objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
JVM uses more memory than just the heap. For example, Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.
The heap is sometimes divided into two areas (or generations) called the nursery (or young space) and the old space. The nursery is a part of the heap reserved for allocation of new objects. When the nursery becomes full, garbage is collected by running a special young collection, where all objects that have lived long enough in the nursery are promoted (moved) to the old space, thus freeing up the nursery for more object allocation. When the old space becomes full garbage is collected there, a process called an old collection.
The reasoning behind a nursery is that most objects are temporary and short lived. A young collection is designed to be swift at finding newly allocated objects that are still alive and moving them away from the nursery. Typically, a young collection frees a given amount of memory much faster than an old collection or a garbage collection of a single-generational heap (a heap without a nursery).]
What is a compaction?
Objects that are allocated next to each other will not necessarily become unreachable (“die”) at the same time. This means that the heap may become fragmented after a garbage collection, so that the free spaces in the heap are many but small, making allocation of large objects hard or even impossible. Free spaces that are smaller than the minimum thread local area (TLA) size can not be used at all, and the garbage collector discards them as dark matter until a future garbage collection frees enough space next to them to create a space large enough for a TLA.
To reduce fragmentation, the JRockit JVM compacts a part of the heap at every garbage collection (old collection). Compaction moves objects closer together and further down in the heap, thus creating larger free areas near the top of the heap. The size and position of the compaction area as well as the compaction method is selected by advanced heuristics, depending on the garbage collection mode used.
In other words, it moves alive objects closer to the bottom of a heap in order to reach them faster and more effectively.
What is weak reference?
Objects wrapped with WeakReference type tell GC that they can be GCed eagerly. That means if there is no strong reference(all references are strong by default in Java) pointing to that object, it is garbage collected. In other words, it only survives GC when a “normal” Java object is pointing to it. The use case is WeakHashMap, which uses weak references for it’s keys. Once a reference to that key is gone and GC happened – the entry is removed.
What is soft reference?
It behaves exactly the same as weak reference, just instead of clearing it on every GC, it only clears before running out of memory. This makes soft references an excellent foundation for a cache.
What is reference queue?
ReferenceQueue is a data structure onto which the garbage collector places reference objects when the reference field is cleared.
What is Phantom reference?
We can’t get a referent of a phantom reference. The referent is never accessible directly through the API and this is why we need a reference queue to work with this type of references. The Garbage Collector adds a phantom reference to a reference queue after the finalize method of its referent is executed. It implies that the instance is still in the memory.
The first technique is to determine when an object was removed from the memory which helps to schedule memory-sensitive tasks. For example, we can wait for a large object to be removed before loading another one.
The second practice is to avoid using the finalize method and improve the finalization process.
What are the differences between processes and threads?
Process is an independent program, which has virtual address, resources, unique process identifier and at least one thread of execution. Usually program starts with one thread as an entry point and then can spawn more threads. A thread is an entity in a process that can be scheduled for execution and it uses resources dedicated for a process.
What is ThreadLocal?
The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. If two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other’s ThreadLocal variables.
How can we achieve thread safety in Java?
- atomic Wrapper classes from java.util.concurrent.atomic package
- locks from java.util.concurrent.locks package
- using thread safe collection classes
- using volatile keyword
What is volatile?
We use volatile in multithreaded applications when we want to share variable between different threads. It acts as is enclosed in a synchronized block on itself. The value of volatile will never be cached thread-locally: all reads and writes will go straight to “main memory”;
What are the differences between synchronized and volatile?
- a primitive variable may be declared volatile (whereas you can’t synchronize on a primitive with synchronized)
- an access to a volatile variable never has the potential to block: we’re only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock
- because accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-write as an atomic operation (unless we’re prepared to “miss an update”)
- a volatile variable that is an object reference may be null (because you’re effectively synchronizing on the reference, not the actual object)
Which is more preferred – synchronized method or synchronized block?
Synchronized block is more preferred way because it doesn’t lock the Object, synchronized methods lock the Object and if there are multiple synchronization blocks in the class, even though they are not related, it will stop them from execution and put them in wait state to get the lock on Object.
What is Thread Group? Why it’s advised not to use it?
Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. ThreadGroup API is weak and it doesn’t have any functionality that is not provided by Thread.
What is Deadlock? How to analyse and avoid deadlock situation?
Deadlock is a state in which each member of a group is waiting for some other member to take action, such as sending a message or more commonly releasing a lock.
To analyze a deadlock, we need to look at the java thread dump of the application, we need to look out for the threads with state as BLOCKED and then the resources it’s waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object.
Compare the sleep() and wait() methods in Java, including when and why you would use one vs. the other.
- sleep() is a blocking operation that locks the shared object for the specified number of milliseconds
- wait(), on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object
- sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll(), to achieve synchronization and avoid race conditions
How can you catch an exception thrown by another thread in Java?
This can be done using Thread.UncaughtExceptionHandler.
What is atomic operation? What are atomic classes in Java Concurrency API?
Atomic operation is a set of actions executed without being interrupted.
Java has java.util.concurrent.atomic package with AtomicBoolean, AtomicInteger, AtomicIntegerArray and etc.
What is Lock interface in Java Concurrency API? What are its’ benefits over synchronization?
A lock is a thread synchronization mechanism like synchronized blocks except locks can be more sophisticated.
Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. Plus it supports multiple associated Condition objects.
What is Callable and Future?
The callable interface is similar to the Runnable interface, but it can return any object, and is able to throw an Exception.
Using Java Future object, we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result. Also Future interface provides cancel(), isDone(), isCanceled()
What is FutureTask Class?
FutureTask is base concrete implementation of Future interface and provides asynchronous processing. It contains the methods to start and cancel a task and also methods that can return the state of the FutureTask as whether it’s completed or cancelled.
What is difference between Error and Exception? Checked/unchecked exceptions
An Error “indicates serious problems that a reasonable application should not try to catch.” An Exception “indicates conditions that a reasonable application might want to catch.” Error along with RuntimeException & their subclasses are unchecked exceptions. All other Exception classes are checked exceptions.
What is exception hierarchy in java?
interviewing 2.1: Java technical questions I <- Previous post