Tuesday, 28 June 2016

Zipping files in Java

In Java java.util.zip package provides classes for data compression and decompression. For compressing data to a ZIP file ZipOutputStream can be used.The ZipOutputStream writes data to an output stream in a ZIP format.

Steps for Zipping data to a file

  • First you need to create a ZipOutputStream object, to which we pass the output stream of the file we wish to write to.
  • Then you also need to create an InputStream for reading the source file.
  • Create a ZipEntry for file that is read.
    ZipEntry entry = new ZipEntry(FILENAME)
    Put the zip entry object using the putNextEntry method of ZipOutputStream
  • That's it now you have a connection between your InputStream and OutputStream. Now read data from the source file and write it to the ZIP file.
  • Finally close the streams.

Java code for zipping sinlge file

 import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileDemo {
    static final int BUFFER = 1024;
    public static void main(String[] args) {
        try{
            // Creating ZipOutputStream
            FileOutputStream fos = new FileOutputStream("G:\\test.zip");
            ZipOutputStream zos = new ZipOutputStream(fos);
            
            
            FileInputStream fis = new FileInputStream("G:\\test.txt");
            BufferedInputStream bis = new BufferedInputStream(fis, BUFFER);
            
            // ZipEntry --- Here file name can be created using the source file
            ZipEntry ze = new ZipEntry("test.txt");
            // Putting zipentry in zipoutputstream
            zos.putNextEntry(ze);
            byte data[] = new byte[BUFFER];
            int count;
            while((count = bis.read(data, 0, BUFFER)) != -1) {
                zos.write(data, 0, count);
            }
            
            zos.close();
            bis.close();
        }catch(IOException ioExp){
            System.out.println("Error while zipping " + ioExp.getMessage());
        }
    }
}
 

Zipping files in folders and subfolders recursively

If you have a folder structure as given below and you want to zip all the files in the parent folder and its sub folders. Then you need to go through the list of files and folders and compress them.

zipping files in Java

Java Code

Here is the Java code that go through the folder structure and zips all files and subfolders recursively. It will even take care of the empty folders in the source folder.

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolderDemo {

    static final int BUFFER = 1024;
    // Source folder which has to be zipped
    static final String FOLDER = "G:\\files";
    List<File> fileList = new ArrayList<File>();
    public static void main(String[] args) {    
        ZipFolderDemo zf = new ZipFolderDemo();
        // get list of files
        List<File> fileList = zf.getFileList(new File(FOLDER));
        //go through the list of files and zip them 
        zf.zipFiles(fileList);    
    }
    
    private void zipFiles(List<File> fileList){
        try{
            // Creating ZipOutputStream - Using input name to create output name
            FileOutputStream fos = new FileOutputStream(FOLDER.concat(".zip"));
            ZipOutputStream zos = new ZipOutputStream(fos);
            // looping through all the files
            for(File file : fileList){
                // To handle empty directory
                if(file.isDirectory()){
                    // ZipEntry --- Here file name can be created using the source file
                    ZipEntry ze = new ZipEntry(getFileName(file.toString())+"/");
                    // Putting zipentry in zipoutputstream
                    zos.putNextEntry(ze);
                    zos.closeEntry();
                }else{
                    FileInputStream fis = new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(fis, BUFFER);
                    // ZipEntry --- Here file name can be created using the source file
                    ZipEntry ze = new ZipEntry(getFileName(file.toString()));
                    // Putting zipentry in zipoutputstream
                    zos.putNextEntry(ze);
                    byte data[] = new byte[BUFFER];
                    int count;
                    while((count = bis.read(data, 0, BUFFER)) != -1) {
                        zos.write(data, 0, count);
                    }
                    bis.close();
                    zos.closeEntry();
                }               
            }                
            zos.close();    
        }catch(IOException ioExp){
            System.out.println("Error while zipping " + ioExp.getMessage());
            ioExp.printStackTrace();
        }
    }
    
    /**
     * This method will give the list of the files 
     * in folder and subfolders
     * @param source
     * @return
     */
    private List<File> getFileList(File source){
        
        if(source.isFile()){
            fileList.add(source);
        }else if(source.isDirectory()){
            String[] subList = source.list();
            // This condition checks for empty directory
            if(subList.length == 0){
                //System.out.println("path -- " + source.getAbsolutePath());
                fileList.add(new File(source.getAbsolutePath()));
            }
            for(String child : subList){
                getFileList(new File(source, child));
            }
        }
        return fileList;
    }
    
    /**
     * 
     * @param filePath
     * @return
     */
    private String getFileName(String filePath){
        String name = filePath.substring(FOLDER.length() + 1, filePath.length());
        //System.out.println(" name " + name);
        return name;
        
    }
}

Zipping files in folders and subfolders recursively in Java 7

If you are using Java 7 or higher then you can use Path and Files.walkFileTree() method to make the code shorter and leave most of the work to API. Here try-with-resources in Java 7 is also used for managing resources automatically.

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolderSeven {
    // Source folder which has to be zipped
    static final String FOLDER = "G:\\files";
    public static void main(String[] args) {
        ZipFolderSeven zs = new ZipFolderSeven();
        zs.zippingInSeven();

    }
private void zippingInSeven(){
        // try with resources - creating outputstream and ZipOutputSttream
        try (FileOutputStream fos = new FileOutputStream(FOLDER.concat(".zip"));
            ZipOutputStream zos = new ZipOutputStream(fos)) {
            
            Path sourcePath = Paths.get(FOLDER);
            // using WalkFileTree to traverse directory
            Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>(){
              @Override
              public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException   {
                    // it starts with the source folder so skipping that 
                    if(!sourcePath.equals(dir)){
                        //System.out.println("DIR   " + dir);
                        zos.putNextEntry(new ZipEntry(sourcePath.relativize(dir).toString() + "/"));
                        
                        zos.closeEntry();    
                    }
                    return FileVisitResult.CONTINUE;
              }
              @Override
              public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                    zos.putNextEntry(new ZipEntry(sourcePath.relativize(file).toString()));
                    Files.copy(file, zos);
                    zos.closeEntry();
                    return FileVisitResult.CONTINUE;
               }
            });
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

That's all for this topic Zipping files in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Unzipping files in Java
  2. How to convert a file to byte array
  3. Reading file in Java using BufferedReader
  4. How to read file from the last line in Java
  5. Reading file in Java using Scanner

You may also like -

>>>Go to Java Programs page

Monday, 27 June 2016

Reading file in Java 8

If anybody asks to point out two most prominent new features of Java 8, I guess most of the people will say Lambda expressions (along with Stream API) and interface default methods. These are definitely impactful changes and lambda expressions along with Streams provides a very easy way to code complex tasks. But that's not all Java 8 also provides another way to read files, you would have used BufferedReader to read files in Java but with Java 8 there is a way to read files using methods of Files class (Files class itself was added in Java 7).

Reading file using Files.readAllLines

readAllLines(Path) method will read all the lines of the file into a list of String. It is not a very efficient way to read a file as a whole file is stored in a list which means consuming more memory.

public class ReadFile {
    public static void main(String[] args) {
        Path path = Paths.get("G:\\Temp.txt");
        
        try {
            List<String> fileList = Files.readAllLines(path);
            System.out.println("" + fileList);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Reading file using Files.lines and Files.newBufferedReader

In Java 8 lines() method has been added in Files class which provide a better way to read files. This method won't read all lines of the file at once but read lines from a file as a Stream line by line.

Another method is newBufferedReader() which returns a BufferedReader to read text from the file in an efficient manner.

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFile {

    public static void main(String[] args) {
        Path path = Paths.get("G:\\Temp.txt");
        // Using Lines
        try(Stream<String> stream = Files.lines(path)){
            stream.forEach(System.out::println);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        // Using newBufferedReader
        try(BufferedReader br = Files.newBufferedReader(path)){
            Stream<String> stream = br.lines();
            stream.forEach(System.out::println);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Since lines and newBufferedReader methods return Stream so you can also use this functional stream to write a chain of streams doing some extra processing.

As example if file has blank lines and you want to filter those blank lines and display only non-blank lines then it can be written this way.

public class ReadFile {

    public static void main(String[] args) {
        Path path = Paths.get("G:\\Temp.txt");
        
        
        try(Stream<String> stream = Files.lines(path)){
            // print only if line is not blank
            stream.filter(line->!line.trim().equals(""))
            .forEach(System.out::println);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

That's all for this topic Reading file in Java 8. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reading file in Java using BufferedReader
  2. How to read file from the last line in Java
  3. How to find last modified date of a file in Java
  4. Reading file in Java using Scanner
  5. Reading delimited file in Java using Scanner
  6. try-with-resources in Java 7

You may also like -

>>>Go to Java Programs page

Friday, 24 June 2016

Reading delimited file in Java using Scanner

A Scanner, when reading input, breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

The scanner can also use delimiters other than whitespace. Scanner class has useDelimiter() method which can be used to change default delimiter. There are two overloaded useDelimiter() methods.

  • useDelimiter(Pattern pattern) - Sets this scanner's delimiting pattern to the specified pattern.
  • useDelimiter(String pattern) - Sets this scanner's delimiting pattern to a pattern constructed from the specified String.

Example Code

Let's see an example where Scanner class is used to read a CSV file.

If there is a CSV file with following data -

Pride And Prejudice,Jane Austen,20.76
The Murder of Roger Ackroyd,Agatha Christie,25.67
Atlas Shrugged,Ayn Rand,34.56
Gone with the Wind,Margaret Mitchell,36.78

And you want to read and parse the line so that you have Book name, author and price as separate strings.

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ScanDelimited {

 public static void main(String[] args) {
  // CSV file
  File file = new File("G:\\Temp.csv");
  Scanner sc = null;
  try {
   sc = new Scanner(file);
   // Check if there is another line of input
   while(sc.hasNextLine()){
    String str = sc.nextLine();
    parseLine(str);
   }
   
  } catch (IOException  exp) {
   // TODO Auto-generated catch block
   exp.printStackTrace();
  }
  
  sc.close();
 }
 
 private static void parseLine(String str){
  String book, author, price;
  Scanner sc = new Scanner(str);
  sc.useDelimiter(",");

  // Check if there is another line of input
  while(sc.hasNext()){
   book = sc.next();
   author = sc.next();
   price = sc.next();
   System.out.println("Book - " + book + " Author - " + author + 
     " Price - " + price);  
  }
  sc.close();
 }
}

Output

Book - Pride And Prejudice Author - Jane Austen Price - 20.76
Book - The Murder of Roger Ackroyd Author - Agatha Christie Price - 25.67
Book - Atlas Shrugged Author - Ayn Rand Price - 34.56
Book - Gone with the Wind Author - Margaret Mitchell Price - 36.78

Example code using pipe (|) symbol as delimiter

If you have a file where pipe is used as delimiter then you can specify a pattern with useDelimiter() method.

Data

Pride And Prejudice|Jane Austen|20.76
The Murder of Roger Ackroyd|Agatha Christie|25.67
Atlas Shrugged|Ayn Rand|34.56
Gone with the Wind|Margaret Mitchell|36.78
package org.netjs.examples1;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ScanDelimited {

 public static void main(String[] args) {
  // delimited file
  File file = new File("G:\\abc.txt");
  Scanner sc = null;
  try {
   sc = new Scanner(file);
   // Check if there is another line of input
   while(sc.hasNextLine()){
    String str = sc.nextLine();
    parseLine(str);
   }
   
  } catch (IOException  exp) {
   // TODO Auto-generated catch block
   exp.printStackTrace();
  }
  
  sc.close();
 }
 
 private static void parseLine(String str){
  String book, author, price;
  Scanner sc = new Scanner(str);
  sc.useDelimiter("[|]");

  // Check if there is another line of input
  while(sc.hasNext()){
   book = sc.next();
   author = sc.next();
   price = sc.next();
   System.out.println("Book - " + book + " Author - " + author + 
     " Price - " + price);  
  }
  sc.close();
 } 
}

Output

Book - Pride And Prejudice Author - Jane Austen Price - 20.76
Book - The Murder of Roger Ackroyd Author - Agatha Christie Price - 25.67
Book - Atlas Shrugged Author - Ayn Rand Price - 34.56
Book - Gone with the Wind Author - Margaret Mitchell Price - 36.78

That's all for this topic Reading delimited file in Java using Scanner. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reading file in Java using Scanner
  2. Reading file in Java using BufferedReader
  3. How to read input from console in Java?
  4. How to read file from the last line in Java

You may also like -

>>>Go to Java Programs page

Wednesday, 22 June 2016

Wiring Collections in Spring

In the post dependency injection in spring you would have seen examples of configuring both property values and reference to other beans. But these attributes property and ref can only be used with single fields. If you want to wire collections then Spring provides four options List, Set, Map and Props.

  • <list> - Used to wire a list of values, works with properties of any type of java.util.Collection and also arrays. As in Java list attribute allows duplicates, order is maintained.
  • <set> - Same as list with couple of differences - doesn’t allow duplicates, insertion order not maintained.
  • <map> - Used to wire a collection of (key, value) pair. Both key and value can be of any type.
  • <props> - Used to wire a collection of (key, value) pair. Both key and value have to be Strings.

Example code using List and Set

Order class

Java class which has both List and Set fields.

import java.util.List;
import java.util.Set;

public class Order {
    private String id;
    private List<String> itemList;
    private Set<String> itemSet;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public List<String> getItemList() {
        return itemList;
    }
    public void setItemList(List<String> itemList) {
        this.itemList = itemList;
    }
    public Set<String> getItemSet() {
        return itemSet;
    }
    public void setItemSet(Set<String> itemSet) {
        this.itemSet = itemSet;
    }   
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    
    <bean id="orderBean" class="org.netjs.prog.Order">
        <property name="id" value = "1" />
        <property name="itemList">
            <list>
                <value>Laptop</value>
                <value>RAM</value>
                <value>Drive</value>
                <value>Drive</value>
            </list>
        </property>
        <property name="itemSet">
            <set>
                <value>Laptop</value>
                <value>RAM</value>
                <value>Drive</value>
                <value>Drive</value>
            </set>
            
        </property>
    </bean>

</beans>

You can run it using the following Java program -

import java.util.List;
import java.util.Set;
import org.netjs.prog.Order;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
       
      Order orderBean = (Order) context.getBean("orderBean");
        List<String> itemList = orderBean.getItemList();
        for(String item : itemList){
            System.out.println("item from List - " + item);
        }
        
        Set<String> itemSet = orderBean.getItemSet();
        for(String item : itemSet){
            System.out.println("item from set - " + item);
        }
    }
}

Output

creating instance of class Admin
creating instance of class Admin
item from List - Laptop
item from List - RAM
item from List - Drive
item from List - Drive
item from set - Laptop
item from set - RAM
item from set - Drive

Here it can be noted that Set has not stored duplicate value.

As mentioned above, List and Set can wire any type of java.util.Collection and also arrays, you can check it by changing the List and Set in Order class respectively to -

private String[] itemList;
private Collection<String> itemSet

without changing anything in XML configuration and it will work just fine.

Bean reference with List and Set

You can reference another bean too while wiring a List or Set.
Let's say we have two classes Order and Item.

Order class

import java.util.List;
import java.util.Set;

public class Order {
    private String id;
    private List<Item> itemList;
    private Set<Item> itemSet;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public List<Item> getItemList() {
        return itemList;
    }
    public void setItemList(List<Item> itemList) {
        this.itemList = itemList;
    }
    public Set<Item> getItemSet() {
        return itemSet;
    }
    public void setItemSet(Set<Item> itemSet) {
        this.itemSet = itemSet;
    }    
}

Item Class

public class Item {
    private String name;
    private double price;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }  
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <bean id="itemBean" class="org.netjs.prog.Item" >
        <property name="name" value = "Laptop" />
        <property name="price" value = "300.45" />
    </bean>
    <bean id="orderBean" class="org.netjs.prog.Order">
        <property name="id" value = "1" />
        <property name="itemList">
            <list>
                <ref bean="itemBean" />
                <bean class="org.netjs.prog.Item">
                    <property name="name" value = "RAM" />
                    <property name="price" value = "34.78" />
                </bean>
            </list>
        </property>
        <property name="itemSet">
            <set>
                <ref bean="itemBean" />
                <bean class="org.netjs.prog.Item">
                    <property name="name" value = "Drive" />
                    <property name="price" value = "50.67" />
                </bean>
            </set>
            
        </property>
    </bean>

</beans>

Note here in Configuration there are two ways to refer another bean, you can either give a reference using ref attribute or within a list attribute you can define a bean.

You can run this using the following Java program -

import org.netjs.prog.Item;
import org.netjs.prog.Order;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
       
        Order orderBean = (Order) context.getBean("orderBean");
        List<Item> itemList = orderBean.getItemList();
        for(Item item : itemList){
            System.out.println("item from List - " + item.getName() + " " + item.getPrice() );
        }
        
        Set<Item> itemSet = orderBean.getItemSet();
        for(Item item : itemSet){
            System.out.println("item from set - " + item.getName() + " " + item.getPrice());
        }
    }
}

Output

creating instance of class Admin
creating instance of class Admin
item from List - Laptop 300.45
item from List - RAM 34.78
item from set - Laptop 300.45
item from set - Drive 50.67

Wiring Map and properties

With Map Key and Value can be String or any other type so there are four options altogether, two for key and two for value.

  • key - Specifies the key of the map entry as a String
  • key-ref - Specifies the key of the map entry as a reference to another bean.
  • value - Specifies the value of the map entry as a String
  • value-ref - Specifies the value of the map entry as a reference to another bean.

With properties both key and value have to be String.

Example Code

Order class

 
import java.util.Map;
import java.util.Properties;

public class Order {
    private String id;
    private Map<String, Item> itemMap;
    private Properties itemProp;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Map<String, Item> getItemMap() {
        return itemMap;
    }
    public void setItemMap(Map<String, Item> itemMap) {
        this.itemMap = itemMap;
    }
    public Properties getItemProp() {
        return itemProp;
    }
    public void setItemProp(Properties itemProp) {
        this.itemProp = itemProp;
    }    
}

Item Class

 
public class Item {
 private String name;
 private double price;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public double getPrice() {
  return price;
 }
 public void setPrice(double price) {
  this.price = price;
 } 
}

XML Configuration

 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    
    <bean id="itemBean" class="org.netjs.prog.Item" >
        <property name="name" value = "Laptop" />
        <property name="price" value = "300.45" />
    </bean>
    <bean id="orderBean" class="org.netjs.prog.Order">
        <property name="id" value = "1" />
        <property name="itemMap">
            <map>
                <entry key="1" value-ref="itemBean" />
                <entry key="2">
                    <bean class="org.netjs.prog.Item">
                        <property name="name" value = "RAM" />
                        <property name="price" value = "34.78" />
                    </bean>
                </entry>
            </map>
        </property>
        <property name="itemProp">
            <props>
                <prop key="Laptop">500</prop>
                <prop key="RAM">56.89</prop>
            </props>
            
        </property>
    </bean>

</beans>

Here note that with Map also reference can be provided using the ref attribute or as inner bean definition.

You can run it using the following Java program -

 
import java.util.Map;
import java.util.Properties;
import org.netjs.prog.Item;
import org.netjs.prog.Order;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
       
    Order orderBean = (Order) context.getBean("orderBean");
    Map<String, Item> itemMap = orderBean.getItemMap();
      for(Map.Entry<String, Item> item : itemMap.entrySet()){
            
      System.out.println("item from Map - " + item.getKey() + " " + item.getValue().getName() + " " +  item.getValue().getPrice());
        }
      Properties itemProp = orderBean.getItemProp();
      System.out.println("items from Properties " + itemProp);
   }
} 

Output

creating instance of class Admin
creating instance of class Admin
item from Map - 1 Laptop 300.45
item from Map - 2 RAM 34.78
items from Properties {Laptop=500, RAM=56.89}

That's all for this topic Wiring Collections in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. What is Dependency Injection in Spring
  2. Dependency Injection using factory-method in Spring
  3. Autowiring using XML configuration in Spring
  4. Autowiring using annotations in Spring
  5. Autodiscovery of bean using componenent-scan in Spring
  6. Data access in Spring framework

You may also like -

>>>Go to Spring tutorial page

Tuesday, 21 June 2016

Blocking methods in Java Concurrency

There are methods in Java which want to execute the task assigned without relinquishing control to other thread. In that case they have to block the current thread in case the condition that fulfil their task is not satisfied.

A very relevant example of blocking methods, which most of you would have encountered is read() method of the InputStream class. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

Then there is accept() method of the ServerSocket class. This method listens for a connection to be made to this socket and accepts it and blocks until a connection is made.

Since this post is more about blocking methods from the Java multi-threading perspective so let's have some example from there.

  • wait() method - Which will block the current thread until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
  • sleep() method - Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
  • join() method - Where the current thread is blocked until all the other threads finish.
  • BlockingQueue and BlockingDeque interfaces - Starting Java 5 with the introduction of java.util.concurrent package blocking data structures which implements these two interfaces BlockingQueue and BlockingDeque have been added. Some of the examples are ArrayBlockingQueue, LinkedBlockingQueue and LinkedBlockingDeque.

    In these data structures put() and take() method are there -

    • put(E e) - Inserts the specified element into this queue, which will block if the space is full.
    • take() - Retrieves and removes element from the queue, waiting if necessary until an element becomes available.

Drawback of blocking methods

Though it is essential to block threads in order to have some synchronization on the execution order or the access on shared object but at the same time blocking threads may lead to suspension of multiple threads even waiting forever if not handled properly posing a serious threat to scalability and performance.

As example - If a thread holding the lock is waiting for some resource like I/O or delayed due to some other fault then other waiting threads will not make any progress.

Non-Blocking Data Structures

Java 5 has added many data structures in concurrency package that use non-blocking algorithm like atomic variables i.e. AtomicInteger, ConcurrentLinkedQueue or reduce the probability of blocking by using techniques like lock striping as used in ConcurrentHashMap.

Non-blocking I/O

Java NIO's non-blocking mode in which an I/O operation will never block and may transfer fewer bytes than were requested or possibly no bytes at all from the Channel.

That's all for this topic Blocking methods in Java Concurrency. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Non-blocking algorithms
  2. Lock Striping in Java Concurrency
  3. BlockingQueue in Java Concurrency
  4. PriorityBlockingQueue in Java Concurrency
  5. BlockingDeque in Java Concurrency

You may also like -

Thursday, 16 June 2016

Reading file in Java using Scanner

Though reading file using BufferedReader remains one of the most used way to read a file but there are other ways to read a file too. Like Scanner class, which was added in Java 5, can be used to read a file.

Scanner is used widely to read input from console as it has a constructor which takes InputStream as argument. But it also has a constructor which takes File as argument and also has methods hasNextLine() and nextLine() to find if there is another line of input and reading the line from input respectively.

One other benefit of using Scanner is it has useDelimiter() method, using this method file delimiter can be set thus making Scanner a good choice for reading and parsing CSV, tab delimited or pipe symbol separated files.

Example code

In the example a File instance is created by passing the file name (file which has to be read) as argument. Then that file instance is passed to Scanner class object. Then file is read using the nextLine() method of the Scanner class.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerRead {

 public static void main(String[] args) {
  File file = new File("G:\\Temp.txt");
  Scanner sc;
  try {
   sc = new Scanner(file);
   // Check if there is another line of input
   while(sc.hasNextLine()){
    String str = sc.nextLine();
    System.out.println("" + str);
   
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  

 }

}

That's all for this topic Reading file in Java using Scanner. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to convert a file to byte array
  2. How to read file from the last line in Java
  3. Reading file in Java using BufferedReader
  4. How to create PDF from XML using Apache FOP

You may also like -

>>>Go to Java Programs page

Tuesday, 14 June 2016

Busy spinning in multi-threading

Busy spinning or busy wait in a multi-threaded environment is a technique where other threads loop continuously waiting for a thread to complete its task and signal them to start.

while(spinningFlag){
 System.out.println("Waiting busy spinning");
}
// Reached here means spinningFlag is false… Now thread can start

Impact of Busy Spinning on performance

Busy spinning is wasteful of CPU cycles as thread just keep running in a loop unless the condition given in the loop satisfies. The main thing to note here is thread doesn't relinquish the CPU control as would be the case if wait(), sleep(), yield() methods are used where the thread gives up the CPU.

Busy spinning may give some advantage in multi-core processors. If a thread relinquishes CPU, the CPU cache for the thread where the thread state, data are stored will also be lost, if the thread resumes its operation on another CPU. In that case it has to rebuild the cache again.

Since thread doesn't relinquish control over CPU when busy spinning so the time spent to create cache again is saved.

But overall it is not a good strategy and should be avoided. At least for the application programs.

Example code

Let's write a Producer - Consumer Java program using busy spinning. Here Producer thread will put 5 elements in the list, consumer thread will be busy waiting until all the 5 elements are added by the producer thread.

import java.util.ArrayList;
import java.util.List;

public class BusySpinDemo {
    
    public static void main(String[] args) {
        ProdThread pt = new ProdThread();
        Thread t1 = new Thread(pt, "Producer");
        // passing producer thread in consumer thread
        Thread t2 = new Thread(new ConThread(pt), "Consumer");
        t1.start();
        t2.start();    
    }
}

// Producer thread
class ProdThread implements Runnable{
    List<Integer> sharedListObj;
    boolean flag;
    ProdThread(){
        System.out.println("Constructor ProdThread");
        this.sharedListObj = new ArrayList<Integer>();
        this.flag = true;
    }
    @Override
    public void run() {
        System.out.println(" ProdThread run");
        for(int i = 0; i < 5; i++){
            System.out.println("Adding to queue - " + Thread.currentThread().getName() + " " + i);
            sharedListObj.add(i);
        }
        flag = false;        
    }            
}

// Consumer thread
class ConThread implements Runnable{
    ProdThread pt;
    ConThread(ProdThread pt){
        System.out.println("Constructor ConThread");
        this.pt = pt;
    }
    @Override
    public void run() { 
      // Busy spinning loop   
        while(this.pt.flag){
            System.out.println("Waiting busy spinning");
        }
        System.out.println("Consumer starting");
        for(Integer i: this.pt.sharedListObj){
            System.out.println("" + i);
        }
    }
}

Output

Constructor ProdThread
Constructor ConThread
 ProdThread run
Waiting busy spinning
Waiting busy spinning
Waiting busy spinning
Waiting busy spinning
Waiting busy spinning
Adding to queue - Producer 0
Waiting busy spinning
Waiting busy spinning
Adding to queue - Producer 1
Waiting busy spinning
Waiting busy spinning
Waiting busy spinning
Waiting busy spinning
Adding to queue - Producer 2
Waiting busy spinning
Waiting busy spinning
Adding to queue - Producer 3
Waiting busy spinning
Adding to queue - Producer 4
Waiting busy spinning
Consumer starting
0
1
2
3
4

Note that the output is curtailed here - Deleted many "Waiting busy spinning" SOPs.

That's all for this topic Busy spinning in multi-threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. ConcurrentLinkedDeque in Java
  2. ConcurrentLinkedQueue in Java
  3. AtomicInteger in Java Concurrency
  4. Synchronization in Java multithreading
  5. ReentrantReadWriteLock in Java
  6. Java Concurrency interview questions

You may also like -

Monday, 13 June 2016

Dependency Injection using factory-method in Spring

As you all know Spring uses dependency injection to create beans and the beans are by default singleton in scope with in the Spring container. Now if you have a Singleton Java class, or a factory class with a static method how will you ensure that only one instance is created which is a singleton within the scope of JVM?

Answer is using factory-method attribute of the bean element.

There may be a case when in a factory class the method which creates an instance of the class is not static in that case you need to use factory-bean attribute along with factory-method attribute.
So we have two scenarios here -

  • Static factory method
  • Non-static (instance) factory method.

Let us see an example to have better understanding.

Example with Singleton class

Let's create a singleton class which lazily loads the class instance and configure it in Spring using factory-method attribute.

Singleton class

package spring_core;

public class Admin {
 // private constructor
 private Admin(){  
 }
 private static class AdminHolder(){
  private static final Admin INSTANCE = new Admin();
 }
 public static Admin getInstance(){
  return AdminHolder.INSTANCE;
 }
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    
    <bean id="adminBean" class="org.netjs.prog.Admin" factory-method="getInstance"/>
    
 
</beans>

You can use the following Java program to run it -

import org.netjs.prog.Admin;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {

 public static void main(String[] args) {
  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
  Admin bean = (Admin) context.getBean("adminBean");
                System.out.println("Values " + bean);
       
                context.close();
 }
}

Output

creating instance of class Admin
Values org.netjs.prog.Admin@343f4d3d

Just to make it clearer that factory-method will help you in creating just a single instance let us have one more example. You must be knowing that Spring uses reflection to instantiate objects and it will invoke constructor regardless of constructor's visibility. Even if there is a private constructor Spring will create an instance of the class. Now you must be wondering then what does factory method do?

If we have the same class as above and in XML configuration we define 4 beans of the same class 2 using factory-method attribute and 2 beans without it.

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    
    <bean id="adminBean" class="org.netjs.prog.Admin" />
    
    <bean id="adminBean1" class="org.netjs.prog.Admin" />
    
    <bean id="adminBean2" class="org.netjs.prog.Admin" factory-method="getInstance"/>
    <bean id="adminBean3" class="org.netjs.prog.Admin" factory-method="getInstance"/>
    
 
</beans>

Java Class

import org.netjs.prog.Admin;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

 public static void main(String[] args) {
  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
  Admin bean = (Admin) context.getBean("adminBean");
                System.out.println("Values " + bean);
                Admin bean1 = (Admin) context.getBean("adminBean1");
                System.out.println("Values " + bean1);
        
                Admin bean2 = (Admin) context.getBean("adminBean2");
                System.out.println("Values " + bean2);
        
                Admin bean3 = (Admin) context.getBean("adminBean3");
                System.out.println("Values " + bean3);
       
                context.close();

 }
}

Output

creating instance of class Admin
creating instance of class Admin
Values org.netjs.prog.Admin@343f4d3d
Values org.netjs.prog.Admin@53b32d7
Values org.netjs.prog.Admin@5442a311
Values org.netjs.prog.Admin@5442a311

If you have noticed first two bean objects are different even if it is a Singleton class and notice the other two objects which are created using factory-method attribute they are same! That's why you need to use factory-method attribute if you want to ensure that your object is singleton.

Example of Factory with static method

As mentioned it's not only with singleton class but also factory with static method where factory-method attribute can be used.
In this example we have a class with 2 arguments and a factory class that create instance of the class.

Test Bean class

public class TestBean {
 private int num;
 private String name;
 public int getNum() {
  return num;
 }
 public void setNum(int num) {
  this.num = num;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }

}

TestBean Factory class

public class TestBeanFactory {
  public static TestBean createTestBean(int num){
   TestBean testBean = new TestBean();
   testBean.setNum(num);
          return testBean;
  }
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    <bean id="testBean" class="org.netjs.prog.TestBeanFactory" factory-method="createTestBean">
        <constructor-arg value = "10" />
        <property name="name" value = "test" />
    </bean>

</beans>

You can run this program using the following Java class -

import org.netjs.prog.TestBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

 public static void main(String[] args) {
  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml"); 
          TestBean testBean = (TestBean) context.getBean("testBean");
          System.out.println("Values " + testBean);
          System.out.println("Name - " + testBean.getName());
 }
}

Example of Factory with non-static method

If you have instance factory method then you can't just use the factory-method attribute as it works with the static method.
As example if I remove the static keyword from the method in the factory class used above -

public class TestBeanFactory {
  public TestBean createTestBean(int num){
   TestBean testBean = new TestBean();
   testBean.setNum(num);
          return testBean;
  }
}

And then try to run it, it will give the following error -

Error creating bean with name 'testBean' defined in class path resource [appcontext.xml]: 
No matching factory method found: factory method 'createTestBean(String)'. 
Check that a method with the specified name and arguments exists and that it is static.

What you need to do in this case is to use factory-bean attribute also along with factory-method attribute.

TestBeanFactory class

public class TestBeanFactory {
  public TestBean createTestBean(int num){
   TestBean testBean = new TestBean();
   testBean.setNum(num);
          return testBean;
  }
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    
    
    <bean id="testBeanFactory" class="org.netjs.prog.TestBeanFactory"/>
    
    <bean id="testBean" class="org.netjs.prog.TestBean" factory-bean="testBeanFactory" factory-method="createTestBean">
        <constructor-arg value = "10" />
        <property name="name" value = "test" />
    </bean>

</beans>

Note that there is definition for Factory class also now. And both factory-bean and factory-method attribute are used.

That's all for this topic Dependency Injection using factory-method in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. What is Dependency Injection in Spring
  2. Constructor-based dependency injection in Spring
  3. How to inject prototype scoped bean in singleton bean
  4. Different bean scopes in Spring
  5. Autowiring using XML configuration in Spring

You may also like -

>>>Go to Spring tutorial page

Friday, 10 June 2016

Non-blocking algorithms in Java

In a multi-threading application if you use a lock or synchronization only one thread at any given time can get hold to the monitor and enter the critical section, all other threads wait for the lock to get free.

Same way, if any data structure has to be used in a multi-threaded environment then it has to use some concurrent algorithm, if that concurrent algorithm allows only one thread at any given time and block all the others then that algorithm is a blocking algorithm. Examples - Synchronized ArrayList or HashMap, implementations of BlockingQueue interface like ArrayBlockingQueue or LinkedBlockingQueue use that kind of lock-based algorithm thus run the risk of blocking the threads (may be for ever).

If a thread holding the lock is waiting for some resource like I/O or delayed due to some other fault then other waiting threads will not make any progress.

As example - If you are using an ArrayBlockingQueue, which is a bounded blocking queue, with capacity as 10. In that case if queue is full and another thread comes to put (using put() method) a value then the thread is blocked until some other thread takes (using take() method) a value out.

Non-blocking algorithm

To prevent the problems as sated above non-blocking algorithm based classes/data structures are introduced in Java starting Java 5. Some of the examples are atomic operation supporting classes like AtomicInteger, AtommicLong and Concurrent collection like ConcurrentLinkedQueue.

An algorithm is called non-blocking if it doesn't block threads in such a way that only one thread has access to the data structure and all the other threads are waiting. Same way failure of any thread in a non-blocking algorithm doesn't mean failure or suspension of other threads.

Compare-And-Swap

Implementation of non-blocking data structures in Java like atomic variables or ConcurrentLinkedQueue use an atomic read-modify-write kind of instruction based on compare-and-swap.

Reference - https://en.wikipedia.org/wiki/Compare-and-swap

According to the description from "Java Concurrency in Practice" by Brian Goetz. CAS has three operands

  1. A memory location M on which to operate
  2. Expected old value OV
  3. New value NV

CAS will match the expected old value OV to the value stored at the memory location M, if both match then only CAS will update the memory location M to the new value NV, otherwise it does nothing. In either case, it returns the value currently in M. The variant of Compare-and-swap called compare-and-set returns a boolean value indicating success/failure of the operation. In Java classes like AtomicInteger compare-and-set method is provided.

When multiple threads attempt to update the same variable simultaneously using CAS, one of those threads wins and updates the variable's value, and the rest lose. But the losers are not punished by suspension, as they could be if they failed to acquire a lock; instead, they are told that they didn't win the race this time but can try again.

Because a thread that loses a CAS is not blocked, it can decide whether it wants to

  • try again,
  • take some other recovery action,
  • or
  • do nothing

As example - At memory location M current value stored is 5, CAS is called by one thread with expected old value as 5 and new value as 6. At the same time another thread tries to change the value at M by passing 6 as old value and 7 as new value.

In that case first thread will succeed in changing the value stored at M to 6 whereas the other thread will report failure as matching for it will fail.

So the point is that threads are not blocked they may fail to get the desired result and may have to call CAS in a loop to get the result, which will result in more CPU cycles but no blocking/failure of threads because one of the thread has acquired lock and not releasing it.

That's all for this topic Non-blocking algorithms in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. ConcurrentLinkedDeque in Java
  2. ConcurrentLinkedQueue in Java
  3. AtomicInteger in Java Concurrency
  4. Synchronization in Java multithreading
  5. ReentrantReadWriteLock in Java
  6. Java Concurrency interview questions

You may also like -

Thursday, 9 June 2016

AtomicInteger in Java Concurrency

AtomicInteger class provides an int value that may be updated atomically. This class resides in the java.util.concurrent.atomic package which has classes that support lock-free, thread-safe programming on single variables. Apart from AtomicInteger some of the other classes are AtomicLong, AtomicReference, DoubleAccumulator.

These atomic variable classes in Java concurrency like AtomicInteger, AtomicLong uses non-blocking algorithm. These non-blocking algorithms use low-level atomic machine instructions such as compare-and-swap instead of locks to ensure data integrity under concurrent access.

Classes in this package java.util.concurrent.atomic provides methods that can get, set or compare value as an atomic operation i.e. without any interruption. There is no need to explicitly use any locking or synchronization.

AtomicInteger Constructor

AtomicInteger class has two constructors -

  • AtomicInteger() - Creates a new AtomicInteger with initial value 0.
  • AtomicInteger(int initialValue) - Creates a new AtomicInteger with the given initial value.

Atomic operations

AtomicInteger class provides atomic methods for getting, setting, incrementing and decrementing variables like getAndIncrement(), getAndDecrement(), decrementAndGet(), getAndSet() etc.

From the method names itself you can easily deduce that these are atomic methods as example if you take getAndIncrement() method which is doing three operatios.

  • Gets the value
  • Increment the value by 1
  • Sets the updated value back

But these 3 operations are done as a single unit i.e. atomic operation. Either all 3 succeed or none.

There is also a compareAndSet(int expect, int update) method which atomically sets the value to the given updated value if the current value is equal to the expected value.

Example code

In banking applications where you need to process several documents there is a very common requirement to provide sequence numbers for the processed documents.

In a multi-threaded environment it can easily be achieved by using AtomicInteger and the atomic operation getAndIncrement().

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntDemo {

 public static void main(String[] args) {
  AtomicInteger ai = new AtomicInteger(0);
  new Thread(new IncThread(ai)).start();
  new Thread(new IncThread(ai)).start();
  new Thread(new IncThread(ai)).start();
 }

}

class IncThread implements Runnable{
 AtomicInteger ai = null;
 IncThread(AtomicInteger ai){
  this.ai = ai;
 }
 
 @Override
 public void run() {
  System.out.println("Value - " + ai.getAndIncrement() + " for " + Thread.currentThread().getName()); 
 }
 
}

Output

Value - 0 for Thread-0
Value - 2 for Thread-2
Value - 1 for Thread-1

Note that output may differ in different runs.

That's all for this topic AtomicInteger in Java Concurrency. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. AtomicLong in Java Concurrency
  2. Non-blocking algorithms
  3. Busy spinning in multi-threading
  4. Blocking methods in Java Concurrency
  5. Java Concurrency interview questions

You may also like -

Tuesday, 7 June 2016

Displaying prime numbers - Java program

As we know that a number is a prime number if it is a natural number greater than 1 and it can be divided either by 1 or by the number itself. As example - 2, 3, 5, 7, 11, 13, 17 ….

If you take any number and check if it has any divisor you will find that by going that number/2 digits starting from 2 it will have a divisor, if one exists.

As example if number is 8 then you just need to check till 4 to see if it divides by any number or take 15 you just need to check till 7 to see if it divides completely by any number. We'll use the same logic to write our program to check for prime number.

Java program

import java.util.Scanner;

public class PrintPrime {

    public static void main(String[] args) {
        // take input from the user
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number till which prime numbers are to be printed - ");
        int num = sc.nextInt();
        for(int i = 2; i <= num; i++){
            if(isPrime(i)){
                System.out.print(i + " ");
            }
        }

    }
    
    private static boolean isPrime(int num){
        boolean flag = true;
        // loop from 2, increment it till number/2
        for(int i = 2; i < num/2; i++){
            // no remainder, means divides 
            if(num % i == 0){
                flag = false;
                break;
            }
        }
        return flag;
    }

}

Output

Enter number till which prime numbers are to be printed - 
50
2 3 4 5 7 11 13 17 19 23 29 31 37 41 43 47

Here scanner class is used to get input from the user.

That's all for this topic Displaying prime numbers - Java program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Checking number prime or not Java program
  2. Armstrong number
  3. Count number of words in a String
  4. How to display pyramid patterns in Java - Part1
  5. How to find all the permutations of the given String

You may also like -

>>>Go to Java Programs page

Monday, 6 June 2016

Checking number prime or not - Java program

As we know that a number is a prime number if it is a natural number greater than 1 and it can be divided either by 1 or by the number itself. As example - 2, 3, 5, 7, 11, 13, 17 ….

First thing that may come to mind is to have a loop that starts from 2 (as 1 will always divide it) and increment it until it reaches the number passed and divide that from the number itself if remainder is zero at any time then it is not a prime number.

That loop would look something like this -

for(int i = 2; i < num; i++){
    if(num % i == 0){
        flag = false;
        break;
    }
}

But that logic can be made more efficient. If you take any number and check if it has any divisor you will find that by going that number/2 digits starting from 2 it will have a divisor, if one exists.

As example if number is 8 then you just need to check till 4 to see if it divides by any number or take 15 you just need to check till 7 to see if it divides completely by any number. We'll use the same logic to write our program to check for prime number.

Java program

import java.util.Scanner;

public class PrimeCheck {

    public static void main(String[] args) {
        // take input from the user
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number - ");
 
             int num = sc.nextInt();
            boolean flag = isPrime(num);
            if(flag){
                System.out.println(num + " is a prime number.");
            }else{
                System.out.println(num + " is not a prime number.");
            }


    }
    
    private static boolean isPrime(int num){
        boolean flag = true;
        // loop from 2, increment it till number/2
        for(int i = 2; i < num/2; i++){
            // no remainder, means divides 
            if(num % i == 0){
                flag = false;
                break;
            }
        }
        return flag;
    }
}

Output

Enter number - 
16
16 is not a prime number.

Enter number - 
31
31 is a prime number.

Here scanner class is used to get input from the user.

That's all for this topic Checking number prime or not - Java program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Displaying prime numbers - Java program
  2. Count total number of times each character appears in a String
  3. Count number of words in a String
  4. How to display pyramid patterns in Java - Part1
  5. How to reverse a string in Java
  6. Armstrong number

You may also like -

>>>Go to Java Programs page

Friday, 3 June 2016

ConcurrentLinkedDeque in Java

ConcurrentLinkedDeque is another concurrent collection which is part of the java.util.concurrent package. Unlike many other concurrent collections like ConcurrentHashMap, CopyOnWriteArrayList which were added in Java 5 ConcurrentLinkedDeque was added in Java 7.

ConcurrentLinkedDeque is an unbounded thread-safe Deque which stores its elements as linked nodes. Since it implements deque interface ConcurrentLinkedDeque supports element insertion and removal at both ends. You will find methods like addFirst(), addLast(), getFirst(), getLast(), removeFirst(), removeLast() to facilitate operations at both ends.

Usage of ConcurrentLinkedDeque

A ConcurrentLinkedDeque is an appropriate choice when many threads will share access to a common collection as concurrent insertion, removal, and access operations execute safely across multiple threads.

Note that it doesn't block operations as done in the implementation of BlockingDequeue interface like LinkedBlockingDeque. So there are no putFirst(), takeFirst() or putLast(), takeLast() methods which will wait if required.

No nulls

Like most other concurrent collection implementations, this class does not permit the use of null elements.

Iterator

Iterators are weakly consistent, returning elements reflecting the state of the queue at some point at or since the creation of the iterator. They do not throw ConcurrentModificationException, and may proceed concurrently with other operations. Elements contained in the queue since the creation of the iterator will be returned exactly once.

Example Code

Let's create a producer consumer using ConcurrentLinkedDeque. In this code there will be one producer thread putting element into the queue and two consumer threads retrieving elements from the queue. Note that producer thread will put 5 elements.

import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentLDeQDemo {

    public static void main(String[] args) {
        //Buffer buffer = new Buffer();
        Deque<Integer> clDQue = new ConcurrentLinkedDeque<Integer>();
        ExecutorService executor = Executors.newFixedThreadPool(3);
        // Calling one producer
        executor.execute(new ProdTask(clDQue));
        // Calling two consumers
        executor.execute(new ConTask(clDQue));
        executor.execute(new ConTask(clDQue));
        executor.shutdown();

    }
    
    

}

/**
 * 
 * 
 *
 */
class ProdTask implements Runnable{
    // Shared Deque object
    Deque<Integer> clDQue;
    ProdTask(Deque<Integer> clDQue){
        this.clDQue = clDQue;
    }
    @Override
    public void run() {
        for(int i = 0; i < 5; i++){
            clDQue.add(i);
        }
    }
}

/**
 * 
 * 
 *
 */
class ConTask implements Runnable{
    Integer value;
    // Shared Deque object
    Deque<Integer> clDQue;
    ConTask(Deque<Integer> clDQue){
        this.clDQue = clDQue;
    }
    @Override
    public void run() {
         while ((value = clDQue.pollFirst()) != null) {
             if(value == null){
                 System.out.println("No value to poll");
             }else{
                 System.out.println("Consumer recd - " + value);
             }
         }
    }    
}

Output

Consumer recd - 0
Consumer recd - 1
Consumer recd - 2
Consumer recd - 3
Consumer recd - 4

That's all for this topic ConcurrentLinkedDeque in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. ConcurrentLinkedQueue in Java
  2. BlockingQueue in Java Concurrency
  3. BlockingDeque in Java Concurrency
  4. LinkedBlockingDeque in Java
  5. ArrayBlockingQueue in Java Concurrency
  6. Java Concurrency interview questions

You may also like -