In this tutorial, we will see how to check if number is power of two.
There are many approaches to check if number is power of two or not.

Approach 1:

It is very easy and straight forward approach.
  • Run a while loop which checks for condition if n is even number (n%2==0).
  • If n is even then divide it by 2 in each iteration.
  • When you get out of while loop and n is equal to 1 then number is power of two,
  • If number is not equal to 1 then number is not power of two.
public static boolean powerOfTwoGeneral(int n)
 {
  while(n%2==0)
  {
   n=n/2;
  }
  if(n==1)
  {
   return true;
  }
  else
  {
   return false;
  }
 }

Approach 2:

We can use bitwise and operator to check if number is power of two or not.
public static boolean powerOfTwoBitwise(int n)
 {
  return (n & n-1)==0;
 }
It will a very simple way to check if number is power of two. Let's see how it works.
Let's say n is 8. Its binary representation will be : 1000.
binary represetation of 7 will be : 0111.
           1 0 0 0
       & 0 1 1 1
         ----------
          0 0 0 0
         ----------
If number is power of 2, then it will have only one bit set to "1".
For example:
8 :   1000
32 : 100000

Similarly when you  check binary form of 7 and 31, it will have all the bits set to "1"
7 :   111
31:  11111
so if you apply bitwise & operator on n and n-1 and result is 0. It means number is power of two.

Java program to check if number is power of two:

package org.arpit.java2blog;

public class PowerOfTwoMain {

 public static void main(String[] args) {
  System.out.println("128 is power of two : "+powerOfTwoGeneral(128));
  System.out.println("64 is power of two : "+powerOfTwoBitwise(64));
  System.out.println("22 is power of two : "+powerOfTwoBitwise(22));
  System.out.println("22 is power of two : "+powerOfTwoGeneral(22));
 }
 // Approach 1
 public static boolean powerOfTwoGeneral(int n)
 {
  while(n%2==0)
  {
   n=n/2;
  }
  if(n==1)
  {
   return true;
  }
  else
  {
   return false;
  }
 }
 // Approach 2
 public static boolean powerOfTwoBitwise(int n)
 {
  return (n & n-1)==0;
 }

}

When you run above code, you will get below results
128 is power of two : true
64 is power of two : true
22 is power of two : false
324 is power of two : false

In my previous articles, I have written about solutions architect exam and list of AWS certifications. AWS is the market leader in the cloud computing platform. If you are planning to switch your career to cloud computing, then AWS is the right place to start your learning process. Microsoft Azure is the only competitor for the AWS platform.
We are going to see a lot of new changes to cloud computing and AWS in the year 2017. Serverless computing is the latest trend in the cloud. Amazon Lambda is an example for the serverless computing and it saves a lot of cost for the companies to move and run their code in the cloud.

AWS certifications are most valuable in the market. With the current demand for cloud engineers across the companies, there is a good amount of requirements seek AWS certifications. I would continue to write in my blog about the AWS certifications and how to prepare for the certifications. If you have any questions, please write it in the comments section.
In this article, we will explain you step by step process on how to effectively prepare for the AWS Certified SysOps Administrator Associate certification exam. This is the toughest exam in the associate level exam. It is a good idea to start from Developer Associate Exam if you are planning to prepare for all the associate level certifications.
The order of the AWS certification preparation should be:
Developer Associate
Solutions Architect Associate
SysOps Administrator Associate
Solutions Architect Professional
DevOps Engineer Professional
We will explore the best approach for studying for the SysOps Administrator Associate certification exam. One of the challenges with preparing for AWS certification is that there is no official study guide for the preparation. You have to mostly depend on the official documentation that are available with AWS website. Also, Amazon keeps adding new services frequently that also will be added to the exams. It is good enough to read the official documentation from Amazon website and practice the questions to pass the exam.

AWS Website:

This will be the first place to start your certification journey. The official website would have all the useful and important details about the certification in the central place. You have to visit the official link for the certification details. You will get all the details like blueprint, sample questions, exam information, video tutorials, etc. Keep this link bookmarked and refer whenever you have any questions about the scope of exam and list of topics that are covered in the exam.
I assume that you have already created a free tier with AWS account. This will help you to use for practice the services.

Exam BluePrint:

The exam blueprint is the official syllabus for the exam. This blueprint explains what are the concepts that are covered in the exam and breakup of the sections and marks that are expected from the each section. This should be the first document one should read for preparing for the exam.
Here is the snapshot of how blueprint shows the list of topics and proportion of exam questions. This would help you lot to prepare for the exam. If you look at the below snapshot, SysOps Administrator exam has the equal amount of questions from all the topics. There are total 7 topics are covered in this exam.

You can also refer the detailed chapters / contents that will be tested in the exam. If you look at the below snapshot, it clearly shows that what are the concepts that are tested in the exam. Note that SysOps exam would not check only the theoretical concepts, more number of questions will be asked in the scenario based real time questions. You should have good experience to answer those questions. 

Whitepapers

This is the collection of documents that offers more in-depth information about each service. This whitepapers contains very useful information about the services. There are several whitepapers available on this page, but you will not be able to read all the documents for the exam. This page also keeps updated with latest whitepapers and reports. Based on the exam topics, you can select few whitepapers and read them.
The following are the important whitepapers that are must read for the exam. Note that this list for preparing the SysOps administrator exam. Other exams will have some other recommended whitepapers.
It is important to read the whitepapers multiple times to get good understanding of the concepts. It is often reported by the exam takers that most of the questions are asked from the whitepapers and that helped them to answer the questions. Note that SysOps exam would expect you to answer the more scenario based questions and deployment related questions.

Practice Questions

Once you have gone through the required study materials, FAQs and whitepapers, then it is the time to take the practice questions. AWS provides few samples questions on the website. But, that is not sufficient for the exam. You have to purchase a good quality practice questions in the market to pass the exam. Whizlabs is one of the most popular practice questions for the AWS certification exam. You can buy their 420 questions and practice well.

Hands on practice

Hands-on experience is definitely the best and efficient way to learn AWS concepts. Nothing can give you more confidence in picking the right answer like having done it yourself. This is one of the most
Unfortunately, this also highlights one of the drawbacks of this kind of certification - sometimes the exams lag behind the real-world. There are some things that the AWS services now do things that aren't reflected in the certification exam.
If you don't have the benefit of using AWS at work, create a new AWS account (i.e. using a new email address) and make the most of the free usage tier. Just set up a billing alarm to send you an email when you are in danger of being charged too much, and you can't go to wrong.

About The Exam

The exam will have 55 multiple choice questions with an 80 minute time limit. Most questions would be single-answer responses, but some are multiple-answer responses. The exact pass mark does change without notice, according to statistical analysis (see the FAQ). 

Also, you have to sign a NDA agreement before taking the exam. You are not allowed to write or talk about the exam details. It is against the policy. So, the practice questions offered by various training are based on the syllabus topics that is shared by Amazon.

Additional Resources

Here is some useful information that would be helpful for you to prepare for this certification exam:
     • Official Link
I hope this article is very informative to understand the basic details that are required to prepare for the AWS Certified SysOps Administrator Associate certification exam. If you have any questions, please write it in the comments section.

Summary

I hope this article is informative and useful for you to prepare for the AWS Certified SysOps Administrator Associate exam. I have explained the important source of information required for preparing this exam. If you have any questions, please write it in the comments section.

In this tutorial, we are going to learn about Android SQLite database CRUD example.
Android SQLite is open source relational database which can be used for performing crud operations.
You don't have to do explicit installation for it. It is available by default in android.

Let's start with simple example:

In this example, we will create a listview to show Country list and support all the CRUD operation with the help of SQLite database. When you will add a new Country to the list or delete any existing country, it will be reflected in the database.

Database Table structure:

Table Name: Country
Column
Data type
Primary key
Id
Integer
Yes
CountryName
Text
No
Population
Long
No

Source code:

Step 1 : Creating Project

Create an android application project named "SQLiteDatabaseCRUDExample".

Step 2: Creating Layout

Change res ->layout -> activity_main.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.java2blog.sqlitedatabasecrudexample.MainActivity">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add Country"
        android:id="@+id/btnSubmit"
        />
    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnSubmit"
        />
</RelativeLayout>

You will see below screen in design view.

Step 3: Create Country class
Create a country class which will correspond to Country table in SQLite database.

package com.java2blog.sqlitedatabasecrudexample;
/*
 * This is our model class and it corresponds to Country table in database
 */

import static android.R.attr.name;

public class Country{

    int id;
    String countryName;
    long population;

    public Country() {
        super();
    }
    public Country(int i, String countryName,long population) {
        super();
        this.id = i;
        this.countryName = countryName;
        this.population=population;
    }

    // constructor
    public Country(String countryName, long population){
        this.countryName = countryName;
        this.population = population;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }

}

Step 4: Create SQLiteDatabaseHandler for defining database operations.

We will create a class called SQLiteDatabaseHandler which will extend SQLiteOpenHelper and override onCreate and OnUpdate method.
We will also add some CRUD methods.
  • addCountry
  • getCountry
  • getAllCountries
  • updateCountry
  • deleteCountry
  • delelteAllCountries
All above methods will interact with SQLite database and perform CRUD operations.
package com.java2blog.sqlitedatabasecrudexample;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

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

public class SQLiteDatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "countryData";

    // Country table name
    private static final String TABLE_COUNTRY= "Country";

    // Country Table Columns names
    private static final String KEY_ID = "id";
    private static final String COUNTRY_NAME = "CountryName";
    private static final String POPULATION = "Population";

    public SQLiteDatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_COUNTRY + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + COUNTRY_NAME + " TEXT,"
                + COUNTRY_NAME + " LONG" + ")";
        db.execSQL(CREATE_COUNTRY_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_COUNTRY);
        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new country
    void addCountry(Country country) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COUNTRY_NAME, country.getCountryName()); // Country Name
        values.put(POPULATION, country.getPopulation()); // Country Population

        // Inserting Row
        db.insert(TABLE_COUNTRY, null, values);
        db.close(); // Closing database connection
    }

    // Getting single country
    Country getCountry(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_COUNTRY, new String[] { KEY_ID,
                        COUNTRY_NAME, POPULATION }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Country country = new Country(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getLong(2));
        // return country
        return country;
    }

    // Getting All Countries
    public List<Country> getAllCountries() {
        List<Country> countryList = new ArrayList<Country>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_COUNTRY;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Country country = new Country();
                country.setId(Integer.parseInt(cursor.getString(0)));
                country.setCountryName(cursor.getString(1));
                country.setPopulation(cursor.getLong(2));
                // Adding country to list
                countryList.add(country);
            } while (cursor.moveToNext());
        }

        // return country list
        return countryList;
    }

    // Updating single country
    public int updateCountry(Country country) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COUNTRY_NAME, country.getCountryName());
        values.put(POPULATION, country.getPopulation());

        // updating row
        return db.update(TABLE_COUNTRY, values, KEY_ID + " = ?",
                new String[] { String.valueOf(country.getId()) });
    }

    // Deleting single country
    public void deleteCountry(Country country) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_COUNTRY, KEY_ID + " = ?",
                new String[] { String.valueOf(country.getId()) });
        db.close();
    }

    // Deleting all countries
    public void deleteAllCountries() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_COUNTRY,null,null);
        db.close();
    }

    // Getting countries Count
    public int getCountriesCount() {
        String countQuery = "SELECT  * FROM " + TABLE_COUNTRY;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }
}

Step 5: Creating layout for Row

As We have declared ListView widget in activity_main.xml. Now we need to provide layout for individual row.
  • Go to res -> layout
  • right click on layout
  • Click on New -> File. 
  • Create a file named "row_item.xml" and paste below code in row_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="30dp"
        android:textColor="#1E90FF"
        android:id="@+id/textViewId"
        android:layout_row="0"
        android:layout_column="1" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="20dp"
        android:textColor="#4B0082"
        android:layout_below="@+id/textViewId"
        android:id="@+id/textViewCountry"
        android:layout_row="1"
        android:layout_column="1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginLeft="10dp"
        android:textSize="20dp"
        android:textColor="#4B0082"
        android:layout_below="@+id/textViewCountry"
        android:id="@+id/textViewPopulation"
        android:layout_row="1"
        android:layout_column="2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="30dp"
        android:id="@+id/edit"
        android:text="Edit"
        android:layout_toRightOf="@+id/textViewId"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnWeight="1"
        android:layout_marginRight="10dp"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="10dp"
        android:id="@+id/delete"
        android:text="Delete"
        android:layout_toRightOf="@+id/edit"
        />
</RelativeLayout>

Step 6:  Creating ArrayAdapter for ListView

Before creating MainActivity, we need to create CustomCountryList class for custom ListView row.
package com.java2blog.sqlitedatabasecrudexample;

import android.app.Activity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;

public class CustomCountryList extends BaseAdapter {
    private Activity context;
    ArrayList<Country> countries;
    private PopupWindow pwindo;
    SQLiteDatabaseHandler db;
    BaseAdapter ba;

    public CustomCountryList(Activity context, ArrayList<Country> countries,SQLiteDatabaseHandler db) {
        this.context = context;
        this.countries=countries;
        this.db=db;
    }

    public static class ViewHolder
    {
        TextView textViewId;
        TextView textViewCountry;
        TextView textViewPopulation;
        Button editButton;
        Button deleteButton;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
            LayoutInflater inflater = context.getLayoutInflater();
            ViewHolder vh;
            if (convertView == null) {
                vh = new ViewHolder();
                row = inflater.inflate(R.layout.row_item, null, true);

                        vh.textViewId = (TextView) row.findViewById(R.id.textViewId);
                        vh.textViewCountry = (TextView) row.findViewById(R.id.textViewCountry);
                        vh.textViewPopulation = (TextView) row.findViewById(R.id.textViewPopulation);
                        vh.editButton = (Button) row.findViewById(R.id.edit);
                        vh.deleteButton = (Button) row.findViewById(R.id.delete);

                // store the holder with the view.
                row.setTag(vh);
            } else {

                    vh = (ViewHolder) convertView.getTag();

            }

            vh.textViewCountry.setText(countries.get(position).getCountryName());
            vh.textViewId.setText("" + countries.get(position).getId());
            vh.textViewPopulation.setText("" + countries.get(position).getPopulation());
            final int positionPopup = position;
            vh.editButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Log.d("Save: ", "" + positionPopup);
                    editPopup(positionPopup);

                }
            });
            vh.deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.d("Last Index", "" + positionPopup);
                    //     Integer index = (Integer) view.getTag();
                    db.deleteCountry(countries.get(positionPopup));

                    //      countries.remove(index.intValue());
                    countries = (ArrayList) db.getAllCountries();
                    Log.d("Country size", "" + countries.size());
                    notifyDataSetChanged();
                }
            });
        return  row;
    }

    public long getItemId(int position) {
        return position;
    }

    public Object getItem(int position) {
        return position;
    }

    public int getCount() {
        return countries.size();
    }

  public void editPopup(final int positionPopup)
  {
      LayoutInflater inflater = context.getLayoutInflater();
      View layout = inflater.inflate(R.layout.edit_popup,
              (ViewGroup) context.findViewById(R.id.popup_element));
      pwindo = new PopupWindow(layout, 600, 670, true);
      pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
      final EditText countryEdit = (EditText) layout.findViewById(R.id.editTextCountry);
      final EditText populationEdit = (EditText) layout.findViewById(R.id.editTextPopulation);
      countryEdit.setText(countries.get(positionPopup).getCountryName());
      populationEdit.setText("" + countries.get(positionPopup).getPopulation());
      Log.d("Name: ", "" + countries.get(positionPopup).getPopulation());
      Button save = (Button) layout.findViewById(R.id.save_popup);
      save.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              String countryStr = countryEdit.getText().toString();
              String population = populationEdit.getText().toString();
              Country country = countries.get(positionPopup);
              country.setCountryName(countryStr);
              country.setPopulation(Long.parseLong(population));
              db.updateCountry(country);
              countries = (ArrayList) db.getAllCountries();
              notifyDataSetChanged();
              for (Country country1 : countries) {
                  String log = "Id: " + country1.getId() + " ,Name: " + country1.getCountryName() + " ,Population: " + country1.getPopulation();
                  // Writing Countries to log
                  Log.d("Name: ", log);
              }
              pwindo.dismiss();
          }
      });
  }
}

This class is used to populating data for ListVIew. getView method is get called for drawing each row.When you click on edit, you will see a popup to edit country Name and population. If you click on delete, country will be deleted from listview and SQLite database.

Step 7: Creating MainActivity

Change src/main/packageName/MainActivity.java as below:
package com.java2blog.sqlitedatabasecrudexample;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<Country> countries;
    SQLiteDatabaseHandler db;
    Button btnSubmit;
    PopupWindow pwindo;
    Activity activity;
    ListView listView;
    CustomCountryList customCountryList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity=this;
        db= new SQLiteDatabaseHandler(this);
        listView = (ListView) findViewById(android.R.id.list);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addPopUp();
                    }
                });
        Log.d("MainActivity: ", "Before reading mainactivity");
        countries = (ArrayList) db.getAllCountries();

            for (Country country : countries) {
                String log = "Id: " + country.getId() + " ,Name: " + country.getCountryName() + " ,Population: " + country.getPopulation();
                // Writing Countries to log
                Log.d("Name: ", log);
            }

                CustomCountryList customCountryList = new CustomCountryList(this, countries, db);
                listView.setAdapter(customCountryList);

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                        Toast.makeText(getApplicationContext(), "You Selected " + countries.get(position).getCountryName() + " as Country", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    public void addPopUp() {
        LayoutInflater inflater = activity.getLayoutInflater();
        View layout = inflater.inflate(R.layout.edit_popup,
                (ViewGroup) activity.findViewById(R.id.popup_element));
        pwindo = new PopupWindow(layout, 600, 670, true);
        pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
        final EditText countryEdit = (EditText) layout.findViewById(R.id.editTextCountry);
        final EditText populationEdit = (EditText) layout.findViewById(R.id.editTextPopulation);

        Button save = (Button) layout.findViewById(R.id.save_popup);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String countryStr = countryEdit.getText().toString();
                String population = populationEdit.getText().toString();
                Country country = new Country(countryStr, Long.parseLong(population));
                db.addCountry(country);
                if(customCountryList==null)
                {
                    customCountryList = new CustomCountryList(activity, countries, db);
                    listView.setAdapter(customCountryList);
                }
                customCountryList.countries = (ArrayList) db.getAllCountries();
                ((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
                for (Country country1 : countries) {
                    String log = "Id: " + country1.getId() + " ,Name: " + country1.getCountryName() + " ,Population: " + country1.getPopulation();
                    // Writing Countries to log
                    Log.d("Name: ", log);
                }
                pwindo.dismiss();
            }
        });
    }
}

When you click on "Add Country" button, you will get a popup.You put Country name and population and Country will be added to the list.

Step 8: Running the app 

When you run the app, you will get below screen:


Click on "Add Country" button and you will get below screen. I have put Country Name as India and Population as 10000.
When you click on save, India will be saved to database. You can similarly add China, Bhutan, and Nepal. You will get below screen.

Let's edit population of china to 20000 to 30000.

When you click on save, China's population will be changed to 30000.
Let's delete Bhutan from list, click on delete corresponding to Bhutan row. When you click on delete, you will get below screen.

Callable interface represents a thread that can return a value. It is very much similar to Runnable interface except that it can return a value. Callable interface can be used to compute status or results that can be returned to invoking thread. For example: Let's say you want to perform factorial and square of some numbers, you can do it concurrently using callable interface which will return value too. Callable defines only one method as below
public interface Callable<v> {
V call() throws Exception;

}
You can define the task which you want to perform inside call method. If it executes successfully, call method will return the result else it must throw an exception. You can use ExecutorService's submit to execute Callable task. Let's see Signature of submit method in ExecutorService.
 <T> Future<T> submit(Callable<T> task);
If you notice, return type of submit method is Future.
Future is generic interface that represents value which will be returned by callable interface. As callable will return value in some future time, name seems suitable here.
There are two methods to get actual value from Future.
get() : When this method is called, thread will wait for result indefinitely.
V get(long timeout, TimeUnit unit) : When this method is called, thread will wait for result only for specified time.

Example:

This program will demonstrate use of Callable and Future. We will create one callable for calculation of square and one callable for factorial. We will submit four tasks to ExecutorService for calculation of square and factorial of 20 and 25. This program will demonstrate how can you make use of Callable and Future to execute it concurrently.
Create class called PowerCalc which implements Callable interface.
package org.arpit.java2blog;
import java.util.concurrent.Callable;
public class PowerCalc implements Callable<Double>{
private double number;
 
 PowerCalc(double number)

public Double call() throws Exception {
{
  this.number=number;
 }
 
 @Override
System.out.println("Calculating Square with "+Thread.currentThread().getName());
Thread.sleep(2000);
  return Math.pow(number, number);
 }

}
Create another class called FactorialCalc which implements Callable interface.
package org.arpit.java2blog;
import java.util.concurrent.Callable;
public class FactorialCalc implements Callable<Double> {
private double number; FactorialCalc(double number) {
public Double call() throws Exception {
this.number = number; } @Override System.out.println("Calculating factorial with "+Thread.currentThread().getName()); Thread.sleep(5000); double fact = 1; for (int i = 2; i <= number; i++) { fact *= i; } return fact; } }
Now create a main classed named FutureCallableMain.java.
package org.arpit.java2blog;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.Executors;

public class FutureCallableMain {


ExecutorService es=Executors.newFixedThreadPool(4);
public static void main(String[] args) {
  System.out.println("Start : ");
  Future<Double> powerFuture20;

powerFuture20=es.submit(new PowerCalc(20));
Future<Double> factorialFuture20;
  Future<Double> powerFuture25;
  Future<Double> factorialFuture25;

factorialFuture25=es.submit(new FactorialCalc(25));
factorialFuture20=es.submit(new FactorialCalc(20));
  powerFuture25=es.submit(new PowerCalc(25));
   try {
System.out.println("Square of "+25+" : "+powerFuture25.get());
System.out.println("Square of "+20+" : "+powerFuture20.get());
    System.out.println("Factorial of "+20+" : "+factorialFuture20.get());

es.shutdown();
System.out.println("Factorial of "+25+" : "+factorialFuture25.get());
   } catch (InterruptedException | ExecutionException e) {
  
    e.printStackTrace();
   } 
  System.out.println("Done");
 }

}
When you run above program, you will get below output:
Start : 
Calculating Square with pool-1-thread-1
Calculating factorial with pool-1-thread-2
Calculating Square with pool-1-thread-3
Square of 20 : 1.048576E26
Calculating factorial with pool-1-thread-4
Factorial of 20 : 2.43290200817664E18
Done
Square of 25 : 8.881784197001253E34
Factorial of 25 : 1.5511210043330986E25
As you can see, we are able to execute 4 tasks concurrently which return square and Factorial of 20 and 25.

Synchronization is ability to restrict access to shared resource to only one thread. When two or more threads need access to shared resource, there has to be some mechanism such that shared resource will be used by only one thread. The process by which we can achieve it is called Synchronization.

Why do you need Synchronization?

Let's understand this with the help of example.
Let's say you want to count number of request you got for a particular URL. If you get two requests at the same time, then count may be inconsistent.

Without Synchronization:

package org.arpit.java2blog;

public class RequestCounter {
 
 private int count;
 
 public int incrementCount()
 {
  count++;
  return count;
 }
}
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 also sees count as 20 and increment it to 21. This shows that count became inconsistent.

With Synchronization:

You can achieve Synchronization using two ways.
  • synchronized method
  • synchronized block
You can not use synchronized with  instance or class variables.

synchronized method

You can make whole incrementCount() method synchronized so no two thread can access it parallelly.
package org.arpit.java2blog;

public class RequestCounter {
 
 private int count;
 
 public synchronized int incrementCount()
 {
  count++;
  return count;
 }
}
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 will now see count as 21 and increment it to 22.

synchronized block

You can make use block to synchronize critical section in  incrementCount() method so no two thread can access block concurrently.
package org.arpit.java2blog;

public class RequestCounter {

 private int count;

 public int incrementCount() {
  synchronized (this) {
   count++;
   return count;
  }
 }
}
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 will now see count as 21 and increment it to 22.

There are two types of locking in java.
  • Object level locking 
  • Class level locking

Object level locking:

Object level locking means you want to synchronize non static method or block so that it can be accessed by only one thread at a time for that instance. It is used if you want to protect non static data.
You can achieve Object level locking by following.

Make method synchronized:

public synchronized int incrementCount()
{
}

Using synchronized block and lock on this:

public int incrementCount() {
  synchronized (this) {
   count++;
   return count;
  }

Using synchronized block and lock on some other object:

private final Object lock=new Object();
public int incrementCount() {
  synchronized (lock) {
   count++;
   return count;
  }

Class level locking:

Class level locking means you want to synchronize static method or block so that it can be accessed by only one thread for whole class. If you have 10 instances of class, only one thread will be able to access only one method or block of any one instance at a time. It is used if you want to protect static data.
This can be achieved by following:

Make static method synchronized:

public static synchronized int incrementCount()
{
}

Using synchronized block and lock on .class:

public int incrementCount() {
  synchronized (RequestCounter.class) {
   count++;
   return count;
  }

Using synchronized block and lock on some other static object:

private final static Object lock=new Object();
public int incrementCount() {
  synchronized (lock) {
   count++;
   return count;
  }

Can two threads execute static and non static methods concurrently? 

Yes, Since two threads will acquire lock on different objects, they can be executed concurrently without any issues.

If one method of class is synchronized and other method of same class is not synchronized? Can they be executed concurrently by two threads?

Yes, because one thread will require lock to get into synchronized block but second thread which will execute non synchronized method that won't require any lock, so it can be executed concurrently.

Is it safe to call a synchronized method from another synchronized method?

Yes, it is safe to call a synchronized method from another synchronized method because when you call synchronized method, you will get lock on this object and when you call another synchronized method of same class, it is safe to execute as it already has lock on this object.
For example:
public synchronized void method1() {
  method2();
  // some code
 }
 
 public synchronized void method2() {
  // some code
 }
You are actually doing this.
public void method1() {
  synchronized (this) {
   method2();
   // some code
  }
  
 }
 
 public void method2() {
  synchronized (this) {
  // some code
  }
 }
Here if any thread calls method2 from method1, it will already have lock on this object hence It is safe to execute.

Exchanger class is introduced with java 1.5 with other classes such ConcurrentHashMap, CountDownLatch, Semaphores.
Exchanger class is used to exchange object between two threads. Exchanger simply waits until two separate threads calls exchange method, when it happens, it exchanges data supplied by threads.Two threads can pair and swap objects between them. Exchanger class may be useful in genetic algorithms or pipeline design.

It has two overloaded version of exchange method.
  • exchange(V x): It waits for another thread to arrive at exchange point and exchange object with that thread. 
  • exchange(V x, long timeout, TimeUnit unit): It waits for another thread for specific time interval provided in the method and exchange object with that thread.

Let's understand with help of example:
We have two threads i.e. Producer and Consumer and they will exchange Country objects. Producer will create Country objects and Consumer will return dummy country objects.


Let's first create Country class. It just have one attribute called countryName.
package org.arpit.java2blog;
public class Country {
  
 private String countryName; 

 public Country(String countryName) {
  super();
  this.countryName = countryName;
 }

 public String getCountryName() {
  return countryName;
 }
}
Now we will create main class called ExchangerExampleMain.java and it will have two other classes called Producer and Consumer which will implement runnable interface.
package org.arpit.java2blog;

import java.util.concurrent.Exchanger;

public class ExchangerExampleMain {

    public static void main(String[] args) {
        Exchanger<Country> exchanger = new Exchanger<Country>();
        // Starting two threads
        new Thread(new Producer(exchanger)).start();
        new Thread(new Consumer(exchanger)).start();
    }
}

class Producer implements Runnable {
   
    Exchanger<Country> ex;
    Producer(Exchanger<Country> ex){
        this.ex = ex;
       
    }
    @Override
    public void run() {
        for(int i = 0; i < 2; i ++){
          Country country=null ;
         if(i==0)
               country =new Country("India");
         else
          country =new Country("Bhutan");
         
            try {
                // exchanging with an dummy Country object
                Country dummyCountry = ex.exchange(country);
                System.out.println("Got country object from Consumer thread : "+dummyCountry.getCountryName());
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }   
    }
}

class Consumer implements Runnable {
  
    Exchanger<Country> ex;
    Consumer(Exchanger<Country> ex){
        this.ex = ex;
    }
    @Override
    public void run() {
        for(int i = 0; i < 2; i ++){
            try {
                // Getting Country object from producer thread
                // giving dummy country object in return
                Country country = ex.exchange(new Country("Dummy"));
                System.out.println("Got country object from Producer thread : "+country.getCountryName());
                
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }       
    }
}
When you run above program, you will get below output.
Got country object from Consumer thread : Dummy
Got country object from Producer thread : India
Got country object from Consumer thread : Dummy
Got country object from Producer thread : Bhutan
If you notice, producer has exchanged two country object (India and Bhutan) with consumer and got dummy country objects in return.
If you want to understand more realistic use of Exchanger. Producer and consumer may exchange buffers. When buffer is full, Producer will provide full buffer to consumer and Consumer will return empty buffer in return.

In this tutorial, we will learn about Executor's newCachedThreadPool factory method.
In the last tutorial, I have shared introduction to ThreadPoolExecutor. If you are not aware of concepts of ThreadPoolExecutor, you should go through that first.

Executor's newCachedThreadPool  factory method :

This method returns an unbounded thread pool. It sets maximum pool size to Integer.Max and it will create new threads depending on demand. If demand decreases, it will tear down threads if threads are idle for more than 1 min.
Example:
Let's create a Task. Here Task will be to read different files and process them.
package org.arpit.java2blog.bean;

public class FetchDataFromFile implements Runnable{
 
 private final String fileName;
 
 public FetchDataFromFile(String fileName) {
  super();
  this.fileName = fileName;
 }
 
 @Override
 public void run() {
  try {
   System.out.println("Fetching data from "+fileName+" by "+Thread.currentThread().getName());
   Thread.sleep(5000); // Reading file
   System.out.println("Read file successfully: "+fileName+" by "+Thread.currentThread().getName());
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 public String getFileName() {
  return fileName;
 }
}
Let's create ThreadPoolExecutor which will consume above task and process it.
package org.arpit.java2blog;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadPoolExecutorMain {
 public static void main(String args[]) {
   // Getting instance of ThreadPoolExecutor using  Executors.newCachedThreadPool factory method
  ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();

  for (int i = 1; i <= 10; i++) {
   FetchDataFromFile fdff = new FetchDataFromFile("File :" + i);
   System.out.println("A new file has been added to read : " + fdff.getFileName());
   threadPoolExecutor.execute(fdff);
  }
  threadPoolExecutor.shutdown();
 }
}
When you run above program, you will get below output:
A new file has been added to read : File :1
A new file has been added to read : File :2
Fetching data from File :1 by pool-1-thread-1
Fetching data from File :2 by pool-1-thread-2
A new file has been added to read : File :3
A new file has been added to read : File :4
Fetching data from File :3 by pool-1-thread-3
Fetching data from File :4 by pool-1-thread-4
A new file has been added to read : File :5
Fetching data from File :5 by pool-1-thread-5
A new file has been added to read : File :6
Fetching data from File :6 by pool-1-thread-6
A new file has been added to read : File :7
Fetching data from File :7 by pool-1-thread-7
A new file has been added to read : File :8
A new file has been added to read : File :9
Fetching data from File :8 by pool-1-thread-8
A new file has been added to read : File :10
Fetching data from File :9 by pool-1-thread-9
Fetching data from File :10 by pool-1-thread-10
If you notice, we have submitted 10 tasks and it has created 10 new threads depending on demand.If any thread remains idle for more than one minute, it will tear it down. newCachedThreadPool is a good choice when you want better queuing performance than newFixedThreadPool. If you want to restrict number of concurrent task for resource management, go with newFixedThreadPool.
 

Java tutorial for beginners Copyright © 2012