Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, April 14, 2015

Java concurrency

 - The use of synchronized methods or statements provides lock acquisition and release to occur in a block-structured way.
 - Lock interface enables lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

Locks
The Lock interface provides more extensive locking operations than it's possible to obtain via synchronized methods and statements
methods:
- void lock()
- void lockInterruptibly()
- Condition newCondition()
- boolean tryLock()
- boolean tryLock(long time, TimeUnit unit)
- void unlock()

ReentrantLock implements Lock:
- ReentrantLock(boolean fair)
creates a reentrant lock with the given fairness policy. Passing true to fair results in a lock that uses a fair ordering policy, which means that under contention, the lock favors granting access to the longest-waiting thread.
- int getHoldCount()
- boolean isFair()
- boolean isHeldByCurrentThread()


ReentrantReadWriteLock implements ReadWriteLock

Condition: Where Lock replaces synchronized methods and statements, Condition replaces Object monitor methods.
additionaly having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations. 

Atomic variables
- Contended synchronization is expensive and throughput suffers as a result.A major reason for the expense is the frequent context switching that takes place; a context switch operation can take many processor cycles to complete.

- volatile variables only solve the visibility problem

The compare-and-swap (CAS) instruction is an uninterruptible instruction that reads a memory location, compares the read value with an expected value, and stores a new value in the memory location when the read value matches the expected value. Otherwise, nothing is done.

java.util.concurrent.atomic offers classes for Boolean (AtomicBoolean), integer (AtomicInteger), long integer (AtomicLong) and reference (AtomicReference) types.


-----------------

- Java Synchronization protects data corruption on race conditions.

Poor way to achieve synchronization.

1. spin lock (Busy wait) - overhead .
2. Sleep lock - Context switching overhead.

ReentrantLock   - re-entrant mutual exclusion lock that extends the built-in monitor lock capabilities.
- Low overhead than ReentrantReadWriteLock

ReentrantReadWriteLock    - improves performance when resource more often read than write.
 - Provides more parallelism on multi core or multi processor hardware

Semaphore - A non-negative integer that controls the access of multiple threads to a limited number of shared resources.

ConditionObject - Block thread until some conditions becomes true.

CountDownLatch - Allow one or more thread to wait until s set of operation being performed in other threads complete.

ConditionObject(uses sleep locks) & Semaphore(uses busy waiting) big overhead than ReentrantLock&ReentrantReadWriteLock


Semaphore & ConditionObject are flexible and provides more capability. 

------------------


reference
http://www.javaworld.com/article/2078848/java-concurrency/java-101-the-next-generation-java-concurrency-without-the-pain-part-2.html

Thursday, March 26, 2015

How to save/store object in Android

Method 1: Save Object as JSON String in SharedPreference

Use GSON Library: It can be used to convert Object in to JSON representation and JSON string to equivalent object.



//To Save
SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(MyObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

//To Retreive
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Method 2: Serializing your object to a private file

Sample Below

//Read Object from File
String devStatusPath = getApplicationContext().getFilesDir() +File.separator +DeviceStatus.class.getSimpleName();
Log.i("[ TEST ]", "ONCREATE PATH = "+devStatusPath);

File file = new File(devStatusPath);

if(file.exists()){
 mDeviceStatus = (DeviceStatus) Serialize
   .readObjectFromFile(getApplicationContext(),
     DeviceStatus.class.getSimpleName());
}

//Write to File
Serialize.witeObjectToFile(getApplicationContext(), mDeviceStatus, DeviceStatus.class.getSimpleName());

//Serialize.java

package com.android.manifesttest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.app.Activity;
import android.content.Context;

public class Serialize {

    public static void witeObjectToFile(Context context, Object object, String filename) {

        ObjectOutputStream objectOut = null;
        try {

            FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
            objectOut = new ObjectOutputStream(fileOut);
            objectOut.writeObject(object);
            fileOut.getFD().sync();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOut != null) {
                try {
                    objectOut.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static Object readObjectFromFile(Context context, String filename) {
        ObjectInputStream objectIn = null;
        Object object = null;
        try {

            FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
            objectIn = new ObjectInputStream(fileIn);
            object = objectIn.readObject();

        } catch (FileNotFoundException e) {
            // Do nothing
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectIn != null) {
                try {
                    objectIn.close();
                } catch (IOException e) {
                }
            }
        }
        return object;
    }
}

Wednesday, March 18, 2015

Java Collection

Array vs Collection

 - Array is best if we know the size of an array.
 - Collection provides growable nature with performance implications.


Difference Between List & Set: 
List Set
- Duplicates Allowed - Not Allowed
- Insertion order Preserved - Not Preserved


Difference Between ArrayList & LinkedList: 

ArrayList LinkedList
1. Best for retrieval operation 1. Best for frequent insert/Delete operation
  (random element access is fast)
  
2. Underlying data structure uses Array 2. Underlying data structure uses Double LL


Vector: 

1. Underlying data structure uses Array.
2. Duplicates allowed.
3. Insertion order preserved
4. NULL object allowed.
5. Heterogeneous objects allowed.
6. Serializable and Clonable.
7. Implements RandomAccess Interface.
8. Thread safe.

- Only difference between ArrayList & Vector is ArrayList is not thread safe. 
- Vector introduced in 1.0 version, before collection framework. So it contains legacy methods. 

Note: How to get synchronized ArrayList object?
 
 ArrayList list1 = new ArrayList();
 
 List list2 = Collections.SynchronizedList(list1);
 
 list2 object is synchronized Array List.
 

HashSet:

1. Underlying data structure uses HashTable.
2. Duplicates Not allowed.
3. Insertion order Not preserved (inserted based on hashcode of object)
4. NULL object allowed.
5. Heterogeneous objects allowed.
6. Serializable and Clonable.
7. Thread safe.
8. Best for Search operations (because of hashcode implementation)  

LinkedHashSet:
- Exactly same as HashSet except the object insertion order is preserved.
- Underlying data structure uses HashTable + Linked List

SortedSet:
- Exactly same as Hashset except the object maintained in order. 
- Default order 1. Ascending for integers 2. Alphabetical for String
- Can define custom comparator to change the default sorting method.
- Null object allowed only once. NPE will happen when objects compared to sort.
- Heterogeneous objects not allowed and all object should implement comparable interface.


TreeSet:
TreeSet same as SortedSet except
- Underlying data structure uses balance Tree.

HashMap vs HashTable

                                   HashMap HashTable
Thread Safe non synchronized and thread safe and not thread safe synchronized Null keys and one null key and any do not allow null keys null values number of null values and null values Iterating the values are iterated by uses enumerator to iterate values using iterator

Note: Hashtable is a subclass of Dictionary class which is not used anymore. It is better off 
externally synchronizing a HashMap or using a ConcurrentMap implementation

Tuesday, March 17, 2015

Design Pattern

Design Pattern:

Design pattern in well defined industry standard approach to solve recurring common software problems. It promotes re-usability 
that leads to more robust, highly maintainable code and it leads to faster development and easy understanding of the code.


Creation Patterns: These design patterns provides way to create objects while hiding the creation logic, rather than instantiating 
       objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case.

Structural Patterns: These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces 
      and define ways to compose objects to obtain new functionalities.
      
Behaviour Patterns: These design patterns are specifically concerned with communication between objects.


behavioural design patterns:
 1. State Design Pattern.
 2. Observer Design pattern - Android Ex: Broadcast receiver
 3. Iterator Pattern - Ex: Java collection framework
 4. Mediator Design Pattern- chat & user list.


structural design pattern:
 1. Adapter design pattern - Android Ex: BaseAdapter, ListAdapter, ArrayAdapter
 2. Proxy Design pattern- Android Ex: ActivityManager, LocationManager and all service manager classes from system process.
 3. Facade Pattern - Ex: MediaPlayer, ContentProvider is kind of Facade Pattern.
 4. Bridge Pattern - decouple an abstraction from its implementation so that the two can vary independently Ex (color & shape abstraction)
 5. Composite Design Pattern - ex: ViewGroup
 6. Decorator Pattern - http://stackoverflow.com/questions/6366385/decorator-pattern-for-io
 7. Flyweight Pattern - String pool 


Creation Design pattern
 1. Factory Pattern - Android Ex: Intent is kind of Factory Pattern
 2. Abstract Factory Design Pattern
 3. Singleton Design Pattern - All system services are singleton classes ActivityManager, Context, LocationManager, TelephonyManager etc...
 4. Builder pattern - Android Ex: Notification.Builder, AlertDialog.Builder
 5. Prototype Pattern - Android Ex: Notification (provides method clone)

Examples of Design Patterns in Java's core libraries

Reference: JournalDev

Friday, February 20, 2015

Thursday, February 19, 2015

Sunday, February 15, 2015

Java Collection Framework Class Hierarchy

List & Queue




Set

Map


overView: