How to convert HashMap to Synchronized Map ?

In this tutorial we will see about how to convert HashMap to synchronized Map. As we know already that HashMap is not synchronized by default.

Synchronize is nothing but making the HashMap to thread safe and by multi-threading environment only one user can remove or edit the Map values. For example if we are using HashMap only for read operation then making synchronized Map is not necessary. Only when multi users or more threads tries to update or remove same key or value from HashMap then we need to make HashMap synchronized for thread safe purpose.

In Java we can do this very easily by using java.util.Collections class as like give below.



Map<String, Object> myMap = new HashMap<String, Object>();
.
.
.  
.
myMap = Collections.synchronizedMap(myMap);


From above code snippet we have declared myMap as HashMap and later in below code we have converted same HashMap instance to synchronized Map. Since this is a simple interview question which asked in 2 to 3 yrs experience level. Hope you are clear now how to convert HashMap to synchronized Map.

Above we have seen how to convert HashMap to SynchronizedMap. Even by converting SynchronizedMap its not guarantee that values will be thread safe we are editing or removing on same Object using multiple Thread. As per  Collections#synchronizedMap() in Oracle docs we need to make operations on Map with synchronized block as mentioned in Oracle docs.  

Lets see all scenarios with details example of 

  1. Accessing updated HashMap without converting to SynchronizedMap under Multi Threading.
  2. Accessing updated HashMap just converting to SynchronizedMap under Multi Threading.
  3. Accessing updated HashMap with converted to SynchronizedMap & Synchronized block under Multi Threading.

Example - 1 : Accessing updated HashMap without converting to SynchronizedMap under Multi Threading.


public class HashMapTest implements Runnable{
 
 // Initializing new HashMap
 private Map<String, String> myMap = new HashMap<String, String>();
 
 public void run() {
  String threadName = Thread.currentThread().getName();
  String oldValue = myMap.get("myKey");
  String newValue = oldValue+threadName;
  myMap.put("myKey", newValue);
  System.out.println(threadName+" : "+myMap.get("myKey"));
 }
 
 public static void main(String[] args) {
  HashMapTest obj = new HashMapTest();
  
  // Adding values into HashMap
  obj.addValues();
  
  // Creating multiple Thread and starting
  for(int i=0;i<5;i++){
   new Thread(obj).start();
  }
  
 }
 public void addValues(){
  myMap.put("myKey", "Java Discover - ");
 }
}


OUTPUT:


Thread-0 : Java Discover - Thread-3
Thread-1 : Java Discover - Thread-3
Thread-2 : Java Discover - Thread-3
Thread-3 : Java Discover - Thread-3
Thread-4 : Java Discover - Thread-3




In above example we have placed 1 value in HashMap and in run() method we trying to upend Thread name to existing value. Each thread names need to be upended in the value, where as we can see only Thread-3 has upended with original value. Remaining 4 Thread names are not updated correctly. Next example lets see just by converting HashMap to SynchronizedMap.



Example - 2 : Accessing updated HashMap just converting to SynchronizedMap under Multi Threading.


public class HashMapTest implements Runnable{
 
 // Initializing new HashMap
 private Map<String, String> myMap = new HashMap<String, String>();
 
 public void run() {
  String threadName = Thread.currentThread().getName();
  String oldValue = myMap.get("myKey");
  String newValue = oldValue+threadName;
  myMap.put("myKey", newValue);
  System.out.println(threadName+" : "+myMap.get("myKey"));
 }
 
 public static void main(String[] args) {
  HashMapTest obj = new HashMapTest();
  
  // Adding values into HashMap
  obj.addValues();
  
  // Converting HashMap to Synchronized Map 
  obj.convertMapToSynMap();
  
  // Creating multiple Thread and starting
  for(int i=0;i<5;i++){
   new Thread(obj).start();
  }
  
 }
 public void convertMapToSynMap(){
  myMap = Collections.synchronizedMap(myMap);
 }
 public void addValues(){
  myMap.put("myKey", "Java Discover - ");
 }
}


OUTPUT:


Thread-0 : Java Discover - Thread-1
Thread-1 : Java Discover - Thread-1
Thread-2 : Java Discover - Thread-1Thread-2
Thread-3 : Java Discover - Thread-1Thread-2Thread-3
Thread-4 : Java Discover - Thread-1Thread-2Thread-3Thread-4



Even by making SynchronizedMap we are getting wrong output when mutiple thread trying to update same Map key value. In above code we can see Thread-0 is missing. Next lets see how to thread safe when we edit under multi threading on same object. 

Example - 3 : Accessing updated HashMap with converted to SynchronizedMap & Synchronized block under Multi Threading.


public class HashMapTest implements Runnable{
 
 // Initializing new HashMap
 private Map<String, String> myMap = new HashMap<String, String>();
 
 public void run() {
  String threadName = Thread.currentThread().getName();
  // Synchronized block 
  synchronized (myMap) {
   String oldValue = myMap.get("myKey");
   String newValue = oldValue+threadName;
   myMap.put("myKey", newValue);
  }  
  System.out.println(threadName+" : "+myMap.get("myKey"));
 }
 
 public static void main(String[] args) {
  HashMapTest obj = new HashMapTest();
  
  // Adding values into HashMap
  obj.addValues();
  
  // Converting HashMap to Synchronized Map 
  obj.convertMapToSynMap();
  
  // Creating multiple Thread and starting
  for(int i=0;i<5;i++){
   new Thread(obj).start();
  }
  
 }
 public void convertMapToSynMap(){
  myMap = Collections.synchronizedMap(myMap);
 }
 public void addValues(){
  myMap.put("myKey", "Java Discover - ");
 }
}

OUTPUT:


Thread-0 : Java Discover - Thread-0Thread-1
Thread-1 : Java Discover - Thread-0Thread-1
Thread-2 : Java Discover - Thread-0Thread-1Thread-2Thread-3
Thread-3 : Java Discover - Thread-0Thread-1Thread-2Thread-3
Thread-4 : Java Discover - Thread-0Thread-1Thread-2Thread-3Thread-4

Now we see all Thread names are upended correctly from 0 to 5. Order doesn't matter since Thread will called according priority. 









How to Create, Write/Append, Read, Delete and Rename a file in Java?

 


We can see in all applications and programs we may need to write or edit file. File operations like creating, deleting, append etc., So in this tutorial we will see about Create, Write, Read and Delete a file using Java code. Each file operations we will discuss with separate program and lets see the output. 
NOTE: File name, path and folder names can vary accordingly. 


1. How to create a file in Java?


public class CreateFile {
    public static void main(String[] args) {
        File myFile = new File("javadiscover.txt");
        try{
        if(!(myFile.exists())){ // checking file exist or not
            myFile.createNewFile(); // Creating new file
            System.out.println("New File created....");
        }else{
            System.out.println("File already exisit....");
        }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}



OUTPUT:


New File created....




2. How to Write/ Append a text into a file in Java ?

public class WriteFile {
    public static void main(String[] args) {
        
        FileWriter fWrite = null;
        BufferedWriter bWrite = null;
        
        String content = "Hi All, Welcome to Java Discover";
        File myFile = new File("javadiscover.txt");
        
        try{
            if(!(myFile.exists())){
                myFile.createNewFile();
        }
        fWrite = new FileWriter(myFile, true); // true for appending content to the existing file
            bWrite = new BufferedWriter(fWrite);
            bWrite.write(content);
            bWrite.close();
            
            System.out.println("File write complete.....");
            
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fWrite != null
                try { fWrite.close(); } catch (IOException e) { e.printStackTrace(); }
            if(bWrite != null
                try { bWrite.close(); } catch (IOException e) { e.printStackTrace(); }            
        }
    }
}



OUTPUT:

Console

File write complete.....


File


3. How to read a file in Java ?


public class ReadFile {
    public static void main(String[] args) {
        BufferedReader br = null;
        try{
            FileReader myFile  = new FileReader("javadiscover.txt");
            br = new BufferedReader(myFile);
            String line = null
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br != null
                try{ br.close(); }catch(IOException e){e.printStackTrace();}
        }        
    }
}


OUTPUT:


Hi All, Welcome to Java Discover
Blog about Java questions and answers


4. How to delete a file in Java ?



public class DeleteFile {
    public static void main(String[] args) {
        try{
            File myFile = new File("javadiscover.txt");
            if(myFile.exists()){
                myFile.delete();
                System.out.println("File deleted successfully....");
            }else{
                System.out.println("File NOT Exisit....");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}



OUTPUT:


File deleted successfully....





5. How to rename a file in Java ?

public class RenameFile {
    public static void main(String[] args) {
        File oriFile = new File("java.txt");
        File newFile = new File("javadiscover.txt");
        if(oriFile.exists()){
            oriFile.renameTo(newFile);
            System.out.println("File rename completed....");
        }else{
            System.out.println("Original file not exist for renaming....");
        }
    }
}



OUTPUT:


File rename completed....





Apart from these examples various file operations which you can refer to Oracle docs.







 

Java Date and Time interview questions




In this tutorial we will see about using Java Date and Time-stamp interview questions as,
1. Getting current local Date and Time
2. Converting current local Date and Time to GMT Date and Time
3. Convert String to Date and Time
4. Convert Date and Time to String
5. Adding N days with current Date and Time
6. Subtracting N days with current Date and Time
7. Change Date and Time format
8. Calculate difference between 2 Date
9. Compare 2 Dates

Lets start with simple examples for all above question on Java Date and Time. In all examples we will be using
SimpleDateFormat()
parse()
format()



1. Getting current local Date and Time

public class MyDateTimeTest {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println("Current Date & Time : "+date);
    }
}

OUTPUT:

Current Date & Time : Sun Mar 17 01:17:30 IST 2013



2. Converting current local Date and Time to GMT Date and Time

public class MyDateTimeTest {
    public static void main(String[] args) {
        Date date = new Date();
        DateFormat gmtFor = new SimpleDateFormat();
        TimeZone gmtTime = TimeZone.getTimeZone("GMT");
          
        gmtFor.setTimeZone(gmtTime);
        System.out.println("Current Date & Time : "+date.toString());
        System.out.println("GMT Time & Date     : " + gmtFor.format(date));
    }
}

OUTPUT:


Current Date & Time : Sun Mar 17 01:29:09 IST 2013
GMT Date & Time     : 3/16/13 7:59 PM



3. Convert String to Date and Time

public class MyDateTimeTest {
    public static void main(String[] args) {
        String myDateTime = "2013-03-17 12:45:56";
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date convertedDateTime = df.parse(myDateTime);
            System.out.println("DATE : "+df.format(convertedDateTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

OUTPUT:
DATE : 2013-03-17 12:45:56




4. Convert Date and Time to String

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date convertedDateTime = new Date();
        String dateInString = df.format(convertedDateTime);
        System.out.println("DATE : "+dateInString);
    }
}

OUTPUT:

DATE : 2013-03-17 02:03:09



5. Adding N days with current Date and Time 

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDateTime = new Date();
        Date newDate = null;
        try {
            newDate = df.parse(df.format(currentDateTime));
            newDate = addNDays(newDate, 10); // Adding 10 days with current Date
            System.out.println("CURRENT DATE              : "+df.format(currentDateTime));
            System.out.println("DATE AFTER ADDING 10 DAYS : "+df.format(newDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
    public static Date addNDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days); 
        return cal.getTime();
    }
}

OUTPUT:

CURRENT DATE              : 2013-03-17 02:17:24
DATE AFTER ADDING 10 DAYS : 2013-03-27 02:17:24



6. Subtracting N days with current Date and Time 

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDateTime = new Date();
        Date newDate = null;
        try {
            newDate = df.parse(df.format(currentDateTime));
            newDate = addNDays(newDate, 10); // Subtracting 10 days with current Date
            System.out.println("CURRENT DATE                   : "+df.format(currentDateTime));
            System.out.println("DATE AFTER SUBTRACTING 10 DAYS : "+df.format(newDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
    public static Date addNDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days*-1); 
        return cal.getTime();
    }
}

OUTPUT:

CURRENT DATE                   : 2013-03-17 02:20:12
DATE AFTER SUBTRACTING 10 DAYS : 2013-03-07 02:20:12



7. Change Date and Time format 

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat df2 = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss aa");
    
        Date currentDateTime = new Date();
        System.out.println("CURRENT DATE      : "+df1.format(currentDateTime));
        System.out.println("NEW FORMATED DATE : "+df2.format(currentDateTime));        
    }
}

OUTPUT:

CURRENT DATE      : 2013-03-17 02:25:59
NEW FORMATED DATE : 17/Mar/2013 02:25:59 AM



8. Calculate difference between 2 Date 

public class MyDateTimeTest {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String otherDate = "2013-03-15 02:38:45";
        
        Date date1 = new Date();
        Date date2 = df.parse(otherDate);
        
        System.out.println("DATE-1 : "+df.format(date1));
        System.out.println("DATE-2 : "+df.format(date2));    
        long diff = date1.getTime() - date2.getTime();
        
        System.out.println("DATE DIFF : "+(diff/ (1000 * 60 * 60)) +" hours");
    }
}

OUTPUT:

DATE-1 : 2013-03-17 02:38:54
DATE-2 : 2013-03-15 02:38:45
DATE DIFF : 48 hours



9. Compare 2 Dates

public class MyDateTimeTest {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String otherDate = "2013-03-15 02:38:45";
        
        Date date1 = new Date();
        Date date2 = df.parse(otherDate);
        
        System.out.println("DATE-1 : "+df.format(date1));
        System.out.println("DATE-2 : "+df.format(date2));    
        
        if(date1.compareTo(date2) > 0){
                System.out.println("Date-1 is after Date-2");
            }else if(date1.compareTo(date2) > 0){
                System.out.println("Date-1 is before Date-2");
            }else if(date1.compareTo(date2) == 0){
                System.out.println("Date-1 is equal to Date-2");
            }
        }



OUTPUT:
DATE-1 : 2013-03-17 02:42:37
DATE-2 : 2013-03-15 02:38:45
Date-1 is after Date-2