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

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.

10/13/2013

8 Useful Mac keyboard shortcuts while editing the text

If you spend a lot of time typing the plain text, writing the program, I suggest that you should remember the below Mac keyboard shortcuts to save your time. Here are a few quick shortcuts to set the matter straight for everyone in Mac OSX.

  1. Command + Right
  2. Move to beginning of line.
  3. Command + Left
  4. Move to end of line.
  5. Command + Up
  6. Move to beginning of document.
  7. Command + Down
  8. Move to end of document.
  9. Command + Delete
  10. Delete the entire line of text or paragraph behind the cursor.
  11. Option + Delete
  12. Delete the entire word behind the cursor.
  13. Shift + Command + Left
  14. Select text to beginning of a line.
  15. Shift + command + Right
  16. select text to end of a line.

8/08/2013

How to re-enable Java SE 6 web plug-in in Google Chrome

I think that this problem of applet not working in chrome (32bits) has plagued me for too long. Now, Apple provided us a resolution which re-enables follow these steps:

Open Terminal, located in the Utilities folder.

sudo mkdir -p /Library/Internet\ Plug-Ins/disabled 
sudo mv /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin /Library/Internet\ Plug-Ins/disabled
sudo ln -sf /System/Library/Java/Support/Deploy.bundle/Contents/Resources/JavaPlugin2_NPAPI.plugin /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin 
sudo ln -sf /System/Library/Frameworks/JavaVM.framework/Commands/javaws /usr/bin/javaws

http://support.apple.com/kb/ht5559