Posts

Showing posts from September, 2017

HashMap in Java

Map in Java has Key-Value pairs To access the value you must know the Key in the HashMap. Hashmap uses a technique of Hashing HashMap does not allow duplicates for the Keys. Below is the simple HashMap program in Java to demonstrate the Key-Value objects in HashMap HashExMain.java: import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class HashExMain {     public static void main (String [] args){         HashMap<Integer, EmployeeDetails> map = new HashMap<Integer, EmployeeDetails>();         EmployeeDetails empOne = new EmployeeDetails(101, "Andrew Heins");         EmployeeDetails empTwo = new EmployeeDetails(102, "Bill patrick");         map.put(1, empOne);         map.put(2, empTwo);         for (HashMap.Entry<Integer, EmployeeDetails> entry : map.entrySet())         {             EmployeeDetails e = entry.getValue();             System.out.println(&q

Threads safety and Synchronization in Java

Thread safety is an utmost important attribute to consider while designing multithreaded applications. Let's understand this with an example PlaneReservationSystem: Suppose two persons "John" and "Jack" want to book the seats on the same flight on the same day. Let's assume that only two seats left on the plane and both John and Jack wants to book two seats as well. Now suppose John and Jack try to book the tickets at the same time, and both of them could see that available seats are 2, but John will get Success of booking message and Jack will get Sorry message. This will create confusion for Jack as he saw available seats 2 but he cannot book the tickets. The reason behind this is that both the person threads are trying to access the same data at the same time causing the problem. Code Synchronization: To avoid this problem we have a feature called code synchronization which restricts multiple threads to access the same code and data at

Threads Basics in Java

Image
A thread is independent and isolated path of execution in single program. Many threads can run concurrently either synchronously or asynchronously with in a single program. Every thread in Java is controlled using Java.lang.Thread class. Check out the YouTube videos of Threads in Java below: Some properties of Threads are : 1. Threads are lightweight processes. 2. Context switching between threads is less expensive. 3. Cost of intercommunication between threads is relatively low. How to create Threads? 1. By extending the Thread class (java.lang.Thread) 2. Implement the Runnable Interface (java.lang.Runnable) Lets see the First method of creating threads by extending the Thread class Code snippet: public class AppWindows extends Thread {        Private String data;        Public AppWindows(String data){        this.data = data;     }        public void run() {             AppWindowsHelper appwindowsHelper =   new AppWindowsHelpe