Monday, August 4, 2008

Java Concurrency In Practice - Book Review

Check my review in javalobby http://java.dzone.com/reviews/java-concurrency-in-practice

Since I started working on java concurrency, I have been looking for a good book on concurrency that is clear, practical and easy to read. 'Java Concurrency in Practice' by Brain Goetz with Doug Lea etc, is by far the best one that I have come across. As opposed to Doug Lea's famous book 'Concurrent Programming in Java: Design Principles and Pattern' which I personally found hard to read and dry in style, this book is extremely well-written and relatively easy to read.

This book is very well organized and divided into four sections, starting from fundamentals like thread safety, atomicity, race conditions, locking, liveliness and goes on to concurrent collections like ConcurrentHaskMap, CopyOnWriteArrayList, BlcokingQueues, ConcurtrentLinkedQueue and other collections.

The second and third sections cover structuring concurrent applications, liveliness, performance and testing which includes Executor framework, boundedbuffers, thread life cycles overheads, context switches, different types of thread pools, thread factories, policies among some very useful techniques for reducing lock contention, lock stripping, avoiding dead locks etc.

I find chapter twelve ‘Testing Concurrent Programs’ particularly interesting and very useful considering how tricky and hard to test concurrent programs in real life.

And the last section covers advanced topics such Explicit locks and advantages and disadvantages of using intrinsic locks vs. explicit locks and read-write locks, performance considerations of using various types of locks, building custom synchronizers, atomic variables and non-blocking synchronization java memory model and annotations.


Recently while working on an application that deals with online advertising similar to Google Adwords and Adsense, I found myself referring to sections two and three very frequently for implementing boundedbuffers with BlockingQueues, ExecutorService and ThreadPools. The code examples presented are very practical and easy to understand.

In the end, this book is a must read for java developers, particularly if you are working with multi-threading and java.concurrenct package.

Wednesday, June 4, 2008

AES Encryption

Recently I had to work on encrypting some data, after doing some research on AES, DES, RC4, I settled on AES. I thought it might be useful to others as well; please feel free to use it. Basically I read key (string) from a file and do the encryption.

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;

/**
* This program generates a AES key, retrieves its raw bytes, and
* then reinstantiates a AES key from the key bytes.
* The reinstantiated key is used to initialize a AES cipher for
* encryption and decryption.
*/

public class Encoders {


public static String doAes (String EncodeSring) throws Exception {

//get key(string) from a file
StringBuilder key = TemplateHandler.getTemplate("aesKeyFile");
byte[] rawKey = stringToKey (key.toString());
SecretKeySpec secretKey = new SecretKeySpec(rawKey, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypted = cipher.doFinal(EncodeSring.getBytes());
return asHex(encrypted);
}



/**
* Turns array of bytes into string
*
* @param buf Array of bytes to convert to hex string
* @return Generated hex string
*/
public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;

for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");

strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}

return strbuf.toString();
}



public static byte[] stringToKey (String password) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance ("MD5");
} catch (NoSuchAlgorithmException ex) {
return new byte[0];
}
byte[] passwordBytes = null;
try {
passwordBytes = password.getBytes ("ISO-8859-1");
} catch (UnsupportedEncodingException ex) {
passwordBytes = new byte[0];
}
return md.digest(passwordBytes);
}
}

Wednesday, May 21, 2008

How to arrange words in a String alphabetically?

Similar to my last post about different way of reversing a string in java, how do you arrange words in Alphabetical order? As with my last post there are many ways one can do it. This is one of those variations. I did it as follows when I had to it for broad matching.

public class ArrangeWordsAlphabetically {

/**

* @param StringToBeOrdered

* Splits keyword at white space and arranges them alphabetically

*/

public String orderAlphabetically(String StringToBeOrdered) {

String stbr = StringToBeOrdered.toLowerCase();

String orderedString = new String();

ArrayList pList = new ArrayList();

String [] tempStr =null;

tempStr = stbr.split("\\s+");

for (int i = 0 ; i <>length ; i++) {

pList.add(tempStr[i]);

}

// sort list

Collections.sort(pList);

// iterate through list

for (String str : pList)

orderedString +=str + " ";

System.out.println(orderedString);

return orderedString;

}

}

How do you reverse words in a String?

I haven’t posted anything in last couple of months as I have been busy with new project. I have been getting lot of requests about sample code for different posts, sorry if I haven’t replied back to you.

Thought I will share something I had to do, other day even though I got asked this question in interviews multiple times over the years.

As we all know there are many different ways of doing it with for loop, while loop, StringToeknizer or Split() etc. Since I have been doing lot of concurrency programming these days using threads, pools, blocking queues, stacks, lists etc, I thought I will try something different as follows.

public class ReverseWords {


public String ReverseStringWords(String StringToBeReversed) {


String reversedString = new String();

Stack stack = new Stack();

String [] tempStr =null;

tempStr = StringToBeReversed.split("\\s+");

for (int i = 0 ; i <>length ; i++) {

stack.push(tempStr[i]);

}

while(!stack.empty()) {

reversedString += (String) stack.pop() + " ";

}

return reversedString.toLowerCase();

}

}

Wednesday, January 9, 2008

Passed SCEA 1 (Sun Certified Enterprise Architect)

I have been planning to write SCEA 1 (Sun Certified Enterprise Architect) certification for last couple months, finally started preparing for it late November. I started with Design Patterns by Head First. Nice read, very entertaining, I highly recommend this book. Next, borrowed UML distilled from Local library. I like this book for the reason that it is very small and concise, gives you basics of UML. As expected EJB is major part of the certification, best place to read specifications is SUN’s website.

One more resource that helped me was Sun Certified Enterprise Architecture for J2EE Technology Study Guide (Sun Microsystems Press). This book contains UML, EJB, Pattern, Security etc all in one place.

I scheduled my exam on Monday 3.00pm so I get whole weekend before the exam to review important topics. There were 48 questions in the exam and I got 43 correct. One word of advise though, try to get as many answers correct as possible on the first pass itself even if takes few seconds more per question than you planned. Make sure you answer all the questions in the first pass. I was expecting to have more time at the end to review few questions I wasn’t sure of, but I ended up having only 2 minutes (2nd pass) to review 18 questions before time was up.

I used following resources.

1. Head First Design Patterns
2. UML Distilled
3. EJB specifications
4. Sun Certified Enterprise Architecture for J2EE Technology Study Guide (Sun Microsystems Press)
5. http://nicky.cust.ipeer.se/moelholmweb/pages/mocks/mocks_scea.xml
6. http://www.geocities.com/subra_73/SCEA_Practice_Questions.htm

Off to part 2…