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.

3/03/2014

Using gist-embed to display code snippet on Blogger


  1. Include Jquery and gist-embed src 
  2. Add a Code HTML element to your page Reference gist-embed