9/18/2014

Switch JDK verson on Mac

When you installed many of jdk versions, there are two ways to switch the jdk.

  • Using Java Preferences application, but Apple decided to remove it.
  • Using java_home in console

After a lot of googing a found simple way solution, I’d like to share.

Edit your profile /.bash_profile or /.zshrc

alias java_ls='/usr/libexec/java_home -V 2>&1 | grep -E "\d.\d.\d[,_]" | cut -d , -f 1 | colrm 1 4 | grep -v Home'

function java_use() {
export JAVA_HOME=$(/usr/libexec/java_home -v $1)
export PATH=$JAVA_HOME/bin:$PATH
java -version
}

Execute java_ls

1.8.0_11
1.7.0_45
1.6.0_65-b14-462
1.6.0_65-b14-462

Execute java_use 1.8

java version "1.8.0_11"
Java(TM) SE Runtime Environment (build 1.8.0_11-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.11-b03, mixed mode)

3/17/2014

Different Between Reader/Writer and InputStream/OutputStream

A Reader/Writer are designed for character-oriented streams. If the information we are reading is all text, then the Reader will take care of character decoding for you. For example, you can read all in text file to represent the characters in Java.

An InputStream/OutStream are designed for byte-oriented streams. It grabs/writes the data byte by byte without performing any kind of translation. For example, you can read/write image data, mp3…or any binary files.

3/14/2014

Observer Pattern

The observer pattern is a behavioral design pattern which defines a one-to-many relationship between objects. When the observable object changes its state, all dependent objects are notified and updated automatically. In stock market case, a stock trading system keeps track of all trades of specific stocks (subjects) and must inform all trader (observers) when a new trade has been made for new prices.

Word Definitions

Observer

someone who sees or notices something

Observable

something that is observable can be seen or measured

Code Example

Event-Bus

To be honest, I don’t want the Observable class to be tightly coupled with the classes that are interested in observing it. It doesn’t care who it is as long as it fulfils certain criteria. I think we might consider the event-bus if there are a lot of usage in your system. There are two reasons :

  • It replaces the tight coupling introduced by explicit listeners with a flexible loosely coupled design.
  • An event bus can be thought of like the observer pattern with an extra layer of decoupling.

Reference Link

3/13/2014

Communicate between Threads in Java

The Java wait-and-notify mechanism is a way for inter thread communcation in Java. It allows one thread to communicate to another thread that a particular condition has occured. The wait-and-notify mechanism cannot be used to replace the synchronized mechanism and does not solve the race condition problem. In fact, wait-and-notify must be used in conjunction with the synchronized lock to prevent a race condition.

Just like the synchronized mechanism, the wait-and-notify mechanism is available from every object. There are three methods to invoke on any object should have the object monitor.

wait, notify and notifyAll methods in Java doc

  • wait()

    The current thread must own this object’s monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object’s monitor to wake up either through a call to the notify method or the notifyAll method.

  • notify()

    Wakes up a single thread that is waiting on this object’s monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object’s monitor by calling one of the wait methods.

  • notifyAll()

    Wakes up all threads that are waiting on this object’s monitor.

On the other question, wait and notify method are used to put thread on wait but they are not in Thread class along with Sleep() or Join() method instead they are declared in Object class. This article has few reasons which make sense on Why Wait and Notify is in Object Class in Java.

Code for Producer-and-Consumer Problem

3/10/2014

Turn Off LinkedIn Activity Broadcast

If you want to search the new job and don’t want your employer to know that you’re updating your profile, I suggested to turn off your activity broadcasts. It’s a good idea to avoid annoying messages. Here’s how to turn off your activity broadcasts.

3/09/2014

Comparable and Comparator in Java

The comparable and Comparator are two interfaces provided by Java Core API. They used to compare stuff in some way for sorting and ordering objects in Java. But what they exactly are and what is different between them? In this tutorial we will see their usage.

Comparable interface

Comparable interface has only one method called compareTo and its purpose is to define the natural ordering of an object. Specifically, compareTo() method should need to return an integer as follows:

  1. a negative integer (–1) if this object is less than the specified object
  2. a positive integer (1) if this object is greater than the specified object
  3. zero integer (0) if this object is equal to specified object

For example consider the real case where we have a Name class:

Comparator interface

Comparator interface gives you the capability to sort a given collection any number of different ways to pas to methods such as Collections.sort() or Arrays.sort(). So you might want to create a Comparator object for the following ideas.

  1. To provide service different ways to sort your objects.
  2. To provide comparison methods for classes that you cannot modify or no control over such String, Date …
  3. To implement strategy pattern for representing an algorithm in which situation to be used.

Sometimes, to write the comparaTo() or compare() methods are very bored and the code will also not be readable. Guava ComparisonChain allows you to check whether an object is less-than or greater-than another object by comparing multiple properties. It should be used the both of Comparable and Comparator.

3/05/2014

Volatile Variable in Java

The volatile variable in Java is a special variable which is used to signal (flag) in multi-threads programming. By the volatile keyword, the application ensures that its value should always been read from heap memory and other threads should not be used cached value of marked volatile variable from thread's stack.

When to Use Volatile

  • Volatile is most useful for lock-free algorithms. You can mark the variable holding shared fields as volatile when you are not using locking to access that variable and you want changes made by one thread to be visible in another.
  • Volatile is used on variables that may be modified simultaneously by other threads.
  • To save cost of synchronization as volatile variables are less expensive than synchronization.

Volatil Example

Useful Links

  • http://mindprod.com/jgloss/volatile.html
  • http://gee.cs.oswego.edu/dl/jmm/cookbook.html
  • http://malalanayake.wordpress.com/2013/09/12/volatile-vs-static-in-java/
  • http://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html

3/04/2014

ThreadLocal class in Java- purpose and use

According to ThreadLocal class in JavaDoc:

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

I think that its purpose is to bind an object to a thread, which has two distinct and useful effects. The binded object is not shared between other threads, so it can be used without the need for synchronization; It is available in period of the life of thread; also meaning you don’t pass it by method calls.

In real cases, Spring security (by default) does in fact store the user information in a Threadlocal variable, the user information can be accessed (assuming you're executing in the same thread as blowed code:

When to use ThreadLocal

  • To wrap any Non-Thread Safe object in ThreadLocal becomes a thread-safe.
  • To implement per thread context information like Security Context.
  • To preserve or carry information from one method call to another, you can carry it by using ThreadLocal.

ThreadLocal class contains four main methods

  • Object get(): Returns the value in the current thread’s copy of this thread-local variable.
  • set(Object): Sets the current thread’s copy of the thread-local variable to the specified value.
  • Object initialValue(): Returns the current thread’s initial value
  • remove(): Removes the current thread’s value for this thread-local variable.

ThreadLocal Example

I think it really simple, we can avoid costly synchronization when a per thread variable is required.

2/23/2014

Overriding equals and hashCode methods in Java

The default implementation of equals() method is provided by Object compares memory location and only return true if the reference variable is pointing to same memory. When overriding equals method, here are the rules that the equals method must obey:
  1. Reflexive: Object must equal to itself.
  2. Symmetric: if a.equals(b) is true and then b.equals(a) must be true.
  3. Transitive: if a.equals(b) is true and then b.equals(c) is be true, then c.equals(a) must be true.
  4. Consistent: multiple invocations of a.equals(b) consistently return true or false, provided no information used in equals comparisons on the objects are modified.
  5. Null comparison: if a.equals(null) should return false.

Step to override equals method

  1. Return true if they are having same address
  2. Return false if the reference object is null
  3. Check subclass or same class by instanceof method
  4. Type cast the object
  5. Compare individual attributes and should avoid NullPointerException
Suppose you are creating a Money class with currency and amount. You could possibly decide that two Money objects must be referring to the same money if they have exactly the same currency and amount fields.

Notice also how verbose Java is, even in an operation as basic as comparing Money for equality. I preferably use the JDK7’s Objects and Guava’s Objects as below:
The new edition of the code will become easier.

Equals and hashCode contract in Java

When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, HashTable, or WeakHashMap…, the hashCode() of key objects that you put into Collection never changes while the object is in the collection.
For equals and hashCode contract, there are two ideas:
  1. If two objects are equal by equals() then their hashCode must be same.
  2. If two objects are having the same hashCode then it does not mean that both objets are equal by equals() method. They might be un-equal also, so their hashCode might be the same or different.

2/18/2014

Java libraries at Google

Here's some things we might know java core libraries at Google.These might be useful for your projects.

  • Guava - java core libraries we find useful in Java projects
  • Dagger - simple & fast dependency injection without reflection
  • Guice - Dagger's reflectiony predecessor
  • Caliper - makes Java microbenchmarking less painful
  • The Auto project - simple, generated value types (AutoValue), factories (AutoFactory) and more
  • Jimfs - full-featured on-heap file system implementation (for java.nio.file)
  • Refaster - syntax-aware refactoring by example (coming soon)
  • Google's Java style guide
  • Square Open Source - Our best friends.

2/15/2014

Parallel, Concurrent and Asynchronous Programming

Parallel Programming

In parallel programming, multiple calculations are executed simultaneously. The computations are typically CPU-intensive and perform either different operations on the same data set or perform the same operation on parts of a data set.

  • To be run using multiple processors
  • A problem is broken into discrete parts that can be solved concurrently
  • Each part is further broken down to a series of instructions
  • Instructions from each part execute simultaneously on different processors
  • An overall control/coordination mechanism is employed

Concurrent Programming

In concurrent programming, programs are designed as computations that interact. The computations may be executed on multiple threads, but also using just a single thread.

  • Multiple threads of control

A number of sequential programs programs work together to achieve a goal.

  • Inter-process Communication

Shared variables and Message passing

  • Synchronization
  1. Mutual exclusion

processes must execute their critical sections one at a time.

  1. Conditional synchronization

processes wait until a condition is true.

Asynchronous Programming

The term asynchronous is used when describing I/O operations that do not block a thread while waiting for completion.

It's common to look at asynchronous processes as non-blocking (the system won't lock up, will continue). Asynchronous programming was typically implemented using callbacks or events.