What is concurrency In Java


Concurrency is general term which means performing multiple task concurrently at same time. Same thing with computers or other computing devices. Everyone knows that computers can perform multiple task at same time.

General Overview

Like while you are writing code in background you can play music and at the same time you can download music even more you can do chat with your friends. This is also know as multi tasking or multi processing.

Even more than one part of a computer program can run concurrently as these are know that Threads. So if a computer program is process then different part of program is thread. Like a word process while you are typing words, same time they are getting displayed on screen and spell checker also checks spelling and highlight is spelling is wrong.

So can CPU execute multiple task at same time, single CPU can execute only one instruction at a time. Modern CPU have more than one processor or core, so multi core CPU can execute multiple instruction at same time.

So, on single core CPU how concurrent processes runs. Answer is OS, OS can schedule CPU time to multiple processes and threads and CPU executes instructions of threads one by one depending on OS context switching and all this happens in very fast and we feel that CPU is executing all programs concurrently.

Applications like Word processor(MS Word), Browser are know as concurrent software(Multi threaded).

Java is designed to create concurrent software with the help of is library with provides several classes to support concurrency.

Processes and Threads

In any concurrent software programming there are two basic execution units know as Process & Thread. And Java is concerned with threads only.

Processes

A process has separate self contained execution environment. You can say any computer program is a process. It has it’s own memory space. But there are many software which are divided into different process, it’s depends upon computer design. Like Eclipse and Java Compiler.

Two processes can communicate with each with IPC mechanism, supported by OS like Sockets, PIPES etc. IPC can be used to communication between two processes running on different systems. Most implementations of the Java virtual machine run as a single process. A Java application can create additional processes using a ProcessBuilder object.

Threads

Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.

Threads exist within a process — every process has at least one. Threads can share the process\’s resources, including memory and open files.

Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread — or several, if you count “system” threads that do things like memory management and signal handling.