Posts

JVM Internals

Image
JVM stands for Java Virtual Machine. Every Java application runs in its own JVM.  It is an engine that runs java applications. JVM is a part of JRE (Java Runtime environment). So on any machine where JRE is installed, we can run java applications. The following shows the architecture diagram of the JVM : JVM has the following areas : 1. ClassLoader subsystem 2. Runtime data area (memory area) 3. Execution engine 4. Native method interface 1. ClassLoader subsytem Classloader is responsible for loading, linking and initialization of the classes. a. Loading involves reading class files and store corresponding data in method area. For each class file, JVM stores fully qualified classname, fully qualified parent class name, constructor info, method info, variable info, constants info, modifiers info, etc. After loading .class files, JVM immediately creates an object for that loaded class on the heap area of the type java. lang.Class. The Class class object can be used

Concurrent collections

With the introduction of concurrency api, the concurrent collections were also introduced. Previously, we had to synchronize the collection object that we are using and at a time, single thread can only access that object. And whenever we do not synchronize and multiple threads perform the operation on the same collection object, we are faced with concurrentmodificationexception. But with these new utilities, multiple threads can perform operations at the same time. Also the performance of the concurrent collections is faster since they use a new type of locking i.e. segment/block locking rather than locking the entire objects. This also makes them suitable for multithreaded, high performance, scalable applications. Following are the concurrent collections : ArrayBlockingQueue ConcurrentHashMap ConcurrentLinkedDeque ConcurrentLinkedQueue ConcurrentSkipListMap ConcurrentSkipListSet CopyOnWriteArrayList CopyOnWriteArraySet DelayQueue LinkedBlockingDeque LinkedBlock

Multithreading - Callable

Many times we would like to have a facility by which we can have return values from the threads. Since the run () method of the Runnable interface has the return type void , it was not possible with that. In the concurrency api, we have a new feature known as the Callable interface. This interface represents a thread that returns a value. The Callable interface defines the single method call() Object call() throws exception The callable task is executed by calling the submit() method of the executor service. Future submit(Callable c) Future is an interface that holds the value returned by the thread. The value can be accessed using the get() method of the Future interface. ExecutorService executorService = Executors. newFixedThreadPool ( 10 ) ; List<ThreadToAddNumbers> list = new ArrayList<ThreadToAddNumbers>() ; for ( int i= 0 ; i< 100 ; i++) { list.add( new ThreadToAddNumbers(i , i*i)) ; } for (ThreadToAddNumbers threadToAddNumbers : list) { F

Multithreading - Executors

Image
Concurrency api comes with a new feature called executor that helps in initializing and controlling the execution of threads. Similar to connection pools, there come thread pools. At the top of the hierarchy is the Executor interface. It comes with a single execute () method. It provides the functionality such that we can remove manual creation of threads. execute(Runnable r) - provide a runnable class and it will manage its thread creation & execution Next is the Executors class. It is a static utility class (similar to Collections) which provides several static factory methods to create various type of Thread Pool implementation in Java. ExecutorService newCachedThreadPool() - returns a thread pool that creates new threads as needed. ExecutorService newFixedThreadPool(int num) - returns a thread pool with threads as specified. ExecutorService newScheduledThreadPool(int num) - returns a thread pool that can schedule                                                

Multithreading - Locks

Traditional multithreaded programming comes with a single way to get the lock i.e. synchronized keyword. All the threads wait until a thread releases the lock i.e. leaves the synchronized block. With the new concurrent api, locks were introduced to give the following facilities : 1. You can try for acquiring a lock, if you get acquire it, if not, you do something else/wait as you wish. 2. You can specify for how much time you want to wait to acquire a lock. This is one of the ways to avoid deadlocks, since thread will not go in a wait state forever. 3. If multiple threads are waiting for a lock, we now have an option to define if the thread waiting for the longest time gets the lock. 4. synchronized keyword was applicable only at method level or block level, but now we have an option to use locks across multiple methods. The locks functionality is present in the java.util.concurrent.locks package starting JDK 1.5 The top interface here is Lock, which defines the basic mecha

Multithreading - Concurrency packages

The original multithreading support in Java does not provide high-level features such as locks, thread pools, execution managers, etc. Java intoduced these features in JDK 5 in the form of concurrent utilities in the java.util.concurrent packages. Following are the features of the concurrency utilities : 1. synchronizers (locks) 2. Executors 3. Concurrent collections 4. Fork/Join framework Before starting lets take a look at thread groups. Every thread in Java,including the main thread, belongs to a thread group. A thread group is a group of threads. In addition to threads, thread groups can also contain sub thread groups.  The usefulness of this concept is that we can do operations, like setting thread priority, on a bunch of threads together rather than doing that for individual threads. ThreadGroup comes with following methods to provide utilities : setMaxPriority() - Any thread added to the thread group will have this priority setDaemon() - sets all the threads in

Multithreading - Daemon Threads

Daemon threads are threads that run in the background. The best example for that is Garbage Collector. Java provides following methods related to daemon threads : 1. isDaemon() - check if the thread is a daemon thread 2. setDaemon() - set the thread to be a daemon thread By default, the main thread is not a daemon thread. All the child threads inherit the daemon nature from the thread that creates them. public class DaemonThreadExample { public static void main (String[] args) { MyThreadExtendingThreadClass t = new MyThreadExtendingThreadClass() ; t.setDaemon( true ) ; t.start() ; // check till how many outputs it generates on the console System. out .println(Thread. currentThread ().isDaemon()) ; System. out .println( "Main thread completed" ) ; } } Daemon threads are automatically terminated when all the non-daemon threads have finished execution. The example for daemon thread can be found  here