Algorithm – Recursion

Algorithm – Recursion

It may be useful to write a separate wrapper routine to do initialization for a complex recursive routine.
Factorial routine that returns all of its intermediate results
int[] allFactorials(int n) { /* Wrapper routine */
int[] results = new int[n == 0 ? 1 : n];
doAllFactorials(n, results, 0);
return results;
}
int doAllFactorials(int n, int[] results, int level) {
if (n > 1) { /* Recursive case */
results[level] = n * doAllFactorials(n - 1, results, level + 1);
return results[level];
} else { /* Base case */
results[level] = 1;
return 1;
}
}
Permutations of a String
Implement a routine that prints all possible orderings of the characters in a string.
Treat each character in the input string as a distinct character, even if it is repeated.
To find all permutations starting at position n, successively place all allowable letters in position n, and for each new letter in position n find all permutations starting at position n + 1 (the recursive case). When n is greater than the number of characters in the input string, a permutation has been completed; print it and return to changing letters at positions less than n (the base case).
If you're past the last position
Print the string
Return
Otherwise
For each letter in the input string
If it's marked as used, skip to the next letter
Else place the letter in the current position
Mark the letter as used
Permute remaining letters starting at current position + 1
Mark the letter as unused
public static void permute(String str) {
int length = str.length();
boolean[] used = new boolean[length];
StringBuffer sb = new StringBuffer();
char[] in = str.toCharArray();
doPermute(in, sb, used, length, 0);
}
private static void doPermute(char[] in, StringBuffer sb, boolean[] used, int length,
int level) {
if (level == length) {
System.out.println(sb.toString());
return;
}
for (int i = 0; i < length; ++i) {
if (used[i])
continue;
sb.append(in[i]);
used[i] = true;
doPermute(in, sb, used, length, level + 1);
used[i] = false;
sb.setLength(sb.length() - 1);
}
}
Combinations of a String
These combinations range in length from one to the length of the string. Two combinations that differ only in ordering of their characters are the same combination.
For each letter from input start position to end of input string
Select the letter into the current position in output string
Print letters in output string
If the current letter isn't the last in the input string
Generate remaining combinations starting at next position with iteration starting
at next letter beyond the letter just selected
public static void combine( String str ){
int length = str.length();
char[] instr = str.toCharArray();
StringBuilder outstr = new StringBuilder();
doCombine( instr, outstr, length, 0, 0 );
}
private static void doCombine( char[] instr, StringBuilder outstr, int length,
int level, int start ){
for( int i = start; i < length; i++ ){
outstr.append( instr[i] );
System.out.println(outstr);
if( i < length - 1 ){
doCombine( instr, outstr, length, level + 1, i + 1 );
}
outstr.setLength(outstr.length() - 1);
}
}
Telephone Words
Write a routine that takes a seven-digit telephone number and prints out all of the possible "words" or combinations of letters that can represent the given number.
You can use the helper routine char getCharKey( int telephoneKey, int place )
If the current digit is past the last digit
Print the word because you're at the end
Else
For each of the three digits that can represent the current digit, going from
low to high
Have the letter represent the current digit
Move to next digit and recurse
If the current digit is a 0 or a 1, return
public static final int PHONE_NUMBER_LENGTH = 7;
public static void printTelephoneWords(int[] phoneNum) {
char[] result = new char[PHONE_NUMBER_LENGTH];
doPrintTelephoneWords(phoneNum, 0, result);
}
private static void doPrintTelephoneWords(int[] phoneNum, int curDigit, char[] result) {
if (curDigit == PHONE_NUMBER_LENGTH) {
System.out.println(String.valueOf(result));
return;
}
for (int i = 1; i <= 3; i++) {
result[curDigit] = getCharKey(phoneNum[curDigit], i);
doPrintTelephoneWords(phoneNum, curDigit + 1, result);
if (phoneNum[curDigit] == 0 || phoneNum[curDigit] == 1)
return;
}
}
Recursive Version:
Create the first word character by character
Loop infinitely:
Print out the word
Increment the last letter and carry the change
If the first letter has reset, you're done
private static final int PHONE_NUMBER_LENGTH = 7;
public static void printTelephoneWords(int phoneNum[]) {
char[] result = new char[PHONE_NUMBER_LENGTH];
int i;
/*
* Initialize the result (in our example, put GWP1WAR in result).
*/
for (i = 0; i < PHONE_NUMBER_LENGTH; i++)
result[i] = getCharKey(phoneNum[i], 1);
/* Main loop begins */
while (true) {
for (i = 0; i < PHONE_NUMBER_LENGTH; ++i) {
System.out.print(result[i]);
}
System.out.print('\n');
/*
* Start at the end and try to increment from right to left.
*/
for (i = PHONE_NUMBER_LENGTH - 1; i >= -1; i--) {
/*
* You're done because you tried to carry the leftmost digit.
*/
if (i == -1)
return;
/* Otherwise, we're not done and must continue. */
/*
* You want to start with this condition so that you can deal
* with the special cases, 0 and 1 right away.
*/
if (getCharKey(phoneNum[i], 3) == result[i] || phoneNum[i] == 0
|| phoneNum[i] == 1) {
result[i] = getCharKey(phoneNum[i], 1);
/* No break, so loop continues to next digit */
} else if (getCharKey(phoneNum[i], 1) == result[i]) {
result[i] = getCharKey(phoneNum[i], 2);
break;
} else if (getCharKey(phoneNum[i], 2) == result[i]) {
result[i] = getCharKey(phoneNum[i], 3);
break;
}
}
}
}
Print number in base m
public final class PrintInt {
private static final String DIGIT_TABLE = "0123456789abcdef";
private static final int MAX_BASE = DIGIT_TABLE.length();
// Print n in any base, recursively
// Precondition: n >= 0, 2 <= base <= MAX_BASE
private static void printIntRec(long n, int base) {
if (n >= base)
printIntRec(n / base, base);
System.out.print(DIGIT_TABLE.charAt((int) (n % base)));
}
// Driver routine
public static void printInt(long n, int base) {
if (base <= 1 || base > MAX_BASE)
System.err.println("Cannot print in base " + base);
else {
if (n < 0) {
n = -n;
System.out.print("-");
}
printIntRec(n, base);
}
}
}

public class BinarySearchRecursive
{
public static final int NOT_FOUND = -1;
public static <AnyType extends Comparable<? super AnyType>> int binarySearch( AnyType [ ] a, AnyType x )
{
return binarySearch( a, x, 0, a.length -1 );
}
// Hidden recursive routine.
private static <AnyType extends Comparable<? super AnyType>>
int binarySearch( AnyType [ ] a, AnyType x, int low, int high )
{
if( low > high )
return NOT_FOUND;
int mid = ( low + high ) / 2;
if( a[ mid ].compareTo( x ) < 0 )
return binarySearch( a, x, mid + 1, high );
else if( a[ mid ].compareTo( x ) > 0 )
return binarySearch( a, x, low, mid - 1 );
else
return mid;
}
}

public class BinarySearch
{
public static final int NOT_FOUND = -1;
public static <AnyType extends Comparable<? super AnyType>>
int binarySearch( AnyType [ ] a, AnyType x )
{
int low = 0;
int high = a.length - 1;
int mid;
while( low <= high )
{
mid = ( low + high ) / 2;
if( a[ mid ].compareTo( x ) < 0 )
low = mid + 1;
else if( a[ mid ].compareTo( x ) > 0 )
high = mid - 1;
else
return mid;
}
return NOT_FOUND; // NOT_FOUND = -1
}
}

Draw Ruler
public class Ruler extends Frame
{
private static final int theSize = 511;
public void paint( Graphics g )
{
drawRuler( g, 10, theSize - 1 + 10, 8 );
}
private void drawRuler( Graphics g, int left, int right, int level)
{
if( level < 1 )
return;
int mid = ( left + right ) / 2;
/*************
***** Uncomment this section to see the drawing in slow motion
try { Thread.sleep( 100 ); }
catch( InterruptedException e ) { }
*************/
g.drawLine( mid, 80, mid, 80 - level * 5 );
drawRuler( g, left, mid - 1, level- 1 );
drawRuler( g, mid + 1, right, level - 1 );
}
// Simple test program
// For simplicity, must terminate from console
public static void main( String [ ] args )
{
Frame f = new Ruler( );
f.setSize( theSize + 20, 110 );
f.setVisible( true );
}
}

Modulo operation
A ≡ B (mod n) if A and B have the same remainder when divided by n, we say that A is equivalent to B, modulo n.
Equivalently, A ≡ B (mod n) if and only if n is A divisor of B - A.
if A ≡ B (mod n), then:
1. A+C ≡ B+C (mod n)
2. AD ≡ BD (mod n)
3. for any positive number P, A^P ≡ B^P (mod n)


X= 3333^5555 (mod 10) = (3333 (mod 10))^5555 (mod 10) = 3^5555 (mod 10)
∵3^4 (mod 10) = 1
∴ X= 3^5555 (mod 10) = (3^4^1388 * 3^3 )(mod 10) = 3^3 (mod 10) = 7

Compute X^N (mod P)
/**
* Return x^n (mod p)
* Assumes x, n >= 0, p > 0, x < p, 0^0 = 1
* Overflow may occur if p > 31 bits.
*/
public static long power( long x, long n, long p )
{
if( n == 0 )
return 1;
long tmp = power( ( x * x ) % p, n / 2, p );
if( n % 2 != 0 )
tmp = ( tmp * x ) % p;
return tmp;
}

Greatest Common Divisor
public static long gcd(long m, long n) {
if (m < n) {
long t = m;
m = n;
n = t;
}
long r = m % n;
if (r == 0) {
return n;
} else {
return gcd(n, r);
}
}

LCD - Lowest common denominator
public static long lcd(long m, long n) {
return m*n/gcd(m,n);
}


Resources:
Data Structures and Problem Solving Using Java
Programming Interviews Exposed: Secrets to Landing Your Next Job, 2nd Edition

Defect - Thread Busy Waiting

Defect - Thread Busy Waiting

Busy waiting is that one thread is active, but doing nothing, just continuously polling some condition, It’s "busy" in as the thread is still executed by the processor, even though the thread is accomplishing nothing but waiting for something. This actually "steals" processor cycles away from other threads.

Busy-waiting can greatly increase the load on the processor, reducing the amount of useful work that other processes can accomplish on the same machine.


In Java, busy waiting can be avoided by any shared object used as a notification mechanism. The waiting thread simply waits (suspends itself temporarily) until the other thread notifies it that it’s done.


For example:

public class CheckRemoteNodeAliveThread extends Thread {

    private HashSet nodeInfoSet = new HashSet();

    private volatile boolean running;

 

    public void checkNodeAlive(RemoteNodeInfo remoteNodeInfo) {

       synchronized (nodeInfoSet) {

           nodeInfoSet.add(remoteNodeInfo);

           // at first, no code below

           // nodeInfoSet.notifyAll();

       }

    }

    public void run() {

       running = true;

       HashSet clonedSet;

       while (running) {

           RemoteNodeInfo remoteNodeInfo = null;

           try {

              // operate on cloned set

              synchronized (nodeInfoSet) {

                  // at first, I forgot to add the following logic, and this would cause busy-wait,

                  // when there are no node in nodeInfoSet, the thread is still continuously poll nodeInfoSet state

                  // while (nodeInfoSet.isEmpty()) {

                  //  nodeInfoSet.wait();

                  // }

                  clonedSet = (HashSet) nodeInfoSet.clone();

                  nodeInfoSet.clear();

              }

              Iterator it = clonedSet.iterator();

              while (it.hasNext()) {

                  // logic to check whether remote node is running

              }

           } catch (Exception e) {

              //this thread is expected to run always, so capture all exception, and do some recover steps

              e.printStackTrace();

           }

       }

    }

}



Resources:
Effective Java (2nd Edition)
Programming Interviews Exposed: Secrets to Landing Your Next Job, 2nd Edition

Bash Command Line Editing

Bash Command Line Editing

Enabling Command-Line Editing

set -o emacs or set -o vi

emacs-mode is more of a natural extension of the minimal editing capability you get with the bare shell.

The History List .bash_history

You can call this file whatever you like by setting the environment variable HISTFILE.

emacs Editing Mode

Basic Commands

CTRL-B Move backward one character (without deleting)

CTRL-F Move forward one character

DEL Delete one character backward

CTRL-D Delete one character forward

Word Commands

ESC-B Move one word backward

ESC-F Move one word forward

ESC-DEL Kill one word backward

ESC-CTRL-H Kill one word backward

ESC-D Kill one word forward

CTRL-Y Retrieve ("yank") last item killed

Line Commands

CTRL-A Move to beginning of line

CTRL-E Move to end of line

CTRL-K Kill forward to end of line

Moving Around in the History List

CTRL-P Move to previous line

CTRL-N Move to next line

CTRL-R Search backward

ESC-< Move to first line of history list

ESC-> Move to last line of history list

Textual Completion

TAB Attempt to perform general completion of the text

ESC- List the possible completions

ESC-/ Attempt filename completion

CTRL-X / List the possible filename completions

ESC-~ Attempt username completion

CTRL-X ~ List the possible username completions

ESC-$ Attempt variable completion

CTRL-X $ List the possible variable completions

ESC-@ Attempt hostname completion

CTRL-X @ List the possible hostname completions

ESC-! Attempt command completion

CTRL-X ! List the possible command completions

ESC-TAB Attempt completion from previous commands in the history list

Miscellaneous Commands

CTRL-L Clears the screen, placing the current line at the top of the screen

CTRL-O Same as RETURN, then display next line in command history

CTRL-O is useful for repeating a sequence of commands you have already entered.

CTRL-T Transpose two characters on either side of point and move point forward by one

CTRL-U Kills the line from the beginning to point

CTRL-V Quoted insert

CTRL-V will cause the next character you type to appear in the command line as is.

ESC-C Capitalize word after point

ESC-U Change word after point to all capital letters

ESC-L Change word after point to all lowercase letters

ESC-. Insert last word in previous command line after point

ESC-_ Same as ESC-.

ESC-. and ESC-_ are useful if you want to run several commands on a given file.

vi Editing Mode

Like vi, vi-mode has two modes of its own: input and control mode

Editing commands in vi input mode

DEL Delete previous character

CTRL-W Erase previous word (i.e., erase until a blank)

CTRL-V Quote the next character

ESC Enter control mode (see below)

Simple Control Mode Commands

h Move left one character

l Move right one character

w Move right one word

b Move left one word

W Move to beginning of next non-blank word

B Move to beginning of preceding non-blank word

e Move to end of current word

E Move to end of current non-blank word

0 Move to beginning of line

^ Move to first non-blank character in line

$ Move to end of line

Entering and Changing Text

i Text inserted before current character (insert)

a Text inserted after current character (append)

I Text inserted at beginning of line

A Text inserted at end of line

R Text overwrites existing text

Deletion Commands

dh Delete one character backwards

dl Delete one character forwards

db Delete one word backwards

dw Delete one word forwards

dB Delete one non-blank word backwards

dW Delete one non-blank word forwards

d$ Delete to end of line

d0 Delete to beginning of line

Abbreviations for vi-mode delete commands

D Equivalent to d$ (delete to end of line)

dd Equivalent to 0d$ (delete entire line)

C Equivalent to c$ (delete to end of line, enter input mode)

cc Equivalent to 0c$ (delete entire line, enter input mode)

X Equivalent to dl (delete character backwards)

x Equivalent to dh (delete character forwards)

Moving Around in the History List

k or - Move backward one line

j or + Move forward one line

G Move to line given by repeat count

/string Search backward for string

?string Search forward for string

n Repeat search in same direction as previous

N Repeat search in opposite direction of previous

Character-Finding Commands

fx Move right to next occurrence of x

Fx Move left to previous occurrence of x

tx Move right to next occurrence of x, then back one space

Tx Move left to previous occurrence of x, then forward one space

; Redo last character-finding command

, Redo last character-finding command in opposite direction

Miscellaneous vi-mode commands

~ Invert (twiddle) case of current character(s)

- Append last word of previous command, enter input mode

CTRL-L Clear the screen and redraw the current line on it; good for when your screen becomes garbled.

# Prepend # (comment character) to the line and send it to the history list; useful for saving a command to be executed later without having to retype it

The fc Command

Purpose Processes the command history list.

Syntax

To Open an Editor to Modify and Reexecute Previously Entered Commands

fc [ -r ] [ -e Editor ] [ First [ Last ] ]

To Generate a Listing of Previously Entered Commands

fc -l [ -n ] [ -r ] [ First [ Last ] ]

To Generate a Listing of Previously Entered Commands with Time of Execution

fc -t [ -n ] [ -r ] [ First [ Last ] ]

To Re-execute a Previously Entered Command

fc -s [ Old= New ] [ First ]

fc -l treats arguments in a rather complex way:

If you give two arguments, they serve as the first and last commands to be shown.

If you specify one number argument, only the command with that number is shown.

With a single string argument, it searches for the most recent command starting with that string and shows you everything from that command to the most recent command.

If you specify no arguments, you will see the last 16 commands you entered. bash also has a built-in command for displaying the history: history.

-n, suppresses the line numbers

fc -l 2 4; fc -l 3; fc -l v; fc -l m w

History Expansion

Event designators

! Start a history substitution

!! Refers to the last command

!n Refers to command line n

!-n Refers to the current command line minus n

!string Refers to the most recent command starting with string

!?string? Refers to the most recent command containing string; the ending is optional

^string1^string2 Repeat the last command, replacing string1 with string2

Word designators

Designator Description

0 The zeroth (first) word in a line

n The nth word in a line

^ The first argument (the second word)

$ The last argument in a line

% The word matched by the most recent ?string search

x-y A range of words from x to y. -y is synonymous with 0-y

* All words but the zeroth (first); synonymous with 1-$.; if there is only one word

on the line, an empty string is returned

x* Synonymous with x-$

x- The words from x to the second to last word

Modifiers

Modifier Description

h Removes a trailing pathname component, leaving the head

r Removes a trailing suffix of the form .xxx

e Removes all but the trailing suffix

t Removes all leading pathname components, leaving the tail

p Prints the resulting command but doesn't execute it

q Quotes the substituted words, escaping further substitutions

x Quotes the substituted words, breaking them into words at blanks and newlines

s/old/new/ Substitutes new for old

Emacs Mpde Keyboard Habits

For cursor motion around a command line, stick to CTRL-A and CTRL-E for beginning

and end of line, and CTRL-F and CTRL-B for moving around.

Delete using DEL (or whatever your "erase" key is) and CTRL-D

Use CTRL-P and CTRL-N (or the up and down arrow keys) to move through the

command history.

Use CTRL-R to search for a command you need to run again.

Use TAB for filename completion.


Resources:

Learning the bash Shell

Java Code Examples


Thread
Thread Cancellation
public class BroadcastThread extends Thread {
    private volatile boolean running; // ===> volatile
    private static BroadcastThread instance;
    private final static long BROADCAST_INTERVAL = 10000;
    private BroadcastThread() {
    }
    public synchronized static BroadcastThread getInstance() {
       if (instance == null) {
           instance = new BroadcastThread();
       }
       return instance;
    }
    public void run() {
       running = true;
       while (running) {
           try {
              broadcastMessages();
              try {
                  Thread.sleep(BROADCAST_INTERVAL);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
           } catch (Exception e) {
              // this thread is expected to continue to run even after hit
              // exception, so capture all exception
              e.printStackTrace();
              // recover
           }
       }
    }
    public void shutdown() {
       running = false;
       interrupt();
    }
    private void broadcastMessages() {
    }
}
Never invoke wait outside a loop

public static void main(String[] args) {
    synchronized (obj) {
        while (<condition does not hold>)
            obj.wait();
            // Perform action appropriate to condition
    }
}
Lazy Initialization Idiom
Initialize-on-demand holder class idiom to lazy initialize a static field:

// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
    static final FieldType field = computeFieldValue();
}
static FieldType getField() { return FieldHolder.field; }  
Use the double-check idiom to lazy initialize a instance field(Only work in JDK5.0 and later):

// Double-check idiom for lazy initialization of instance fields
private volatile FieldType field;
public FieldType getField() {
    if (field == null) { // First check (no locking)
       synchronized(this) {
           if (field == null) // Second check (with locking)
              field = computeFieldValue();
       }
    }
    return field;
}
Design Pattern - Singleton
public class EagerSingleton {
     private static final EagerSingleton instance = new EagerSingleton();
     private EagerSingleton() {
     }
     public static EagerSingleton getInstance() {
         return instance;
     }
}




public class LazySingleton {
     private static LazySingleton instance;
     private LazySingleton() {
     }
     public static synchronized LazySingleton getInstance() {
         if (instance == null) {
              instance = new LazySingleton();
         }
         return instance;
     }
}
IO:

public class SerializationUtils {
    public static Object deserialize(String filename)
            throws FileNotFoundException, IOException, ClassNotFoundException {
        Object object = null;
        FileInputStream fis = null;
        ObjectInputStream in = null;
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        object =  in.readObject();
        in.close();
        return object;
    }
    public static void serialize(String filename, Object object)
            throws FileNotFoundException, IOException {
        FileOutputStream fos = null;
        ObjectOutputStream out = null;
        fos = new FileOutputStream(filename);
        out = new ObjectOutputStream(fos);
        out.writeObject(object);
        out.flush();
        out.close();
    }
}
Read/Write object with ByteArrayInputStream/ByteArrayOutputStream

ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeInt(20);
oout.flush();

byte[] bytes = bout.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
ObjectInputStream oin = new ObjectInputStream(bin);
System.out.println(oin.readInt());
Have a multi-line value in a properties file
You add a slash ("\") to continue the value on the next line.

MessageFormat
String result = MessageFormat
       .format("The book with title {0} is sold with price {1,number,currency} to {2}",new Object[] { title, price, buyername });
MessageFormat form = new MessageFormat(
       "The disk \"{1}\" contains {0} file(s).");
System.out.println(form.format(testArgs));
Load resources from the classpath
BufferedReader reader = new BufferedReader(new InputStreamReader(this
       .getClass().getResourceAsStream(filePath)));
Network
Print all local address:
public static void printAllLocalAddress() throws SocketException
{
    Enumeration nis = NetworkInterface.getNetworkInterfaces();
    while( nis.hasMoreElements() )
    {
        NetworkInterface ni = (NetworkInterface)nis.nextElement();
        //Enumerate InetAddress of this network interface
        Enumeration addresses = ni.getInetAddresses();
        while( addresses.hasMoreElements() )
        {
            InetAddress address = (InetAddress)addresses.nextElement();
            System.out.println(address);
        }
    }
}

Java Out Of Memory Error

Java Out Of Memory Error

java.lang.OutOfMemoryError: Java heap space
This common error indicates that an object creation failed because there was no available heap space for it. It will never be thrown unless the JVM tries a full garbage collection first, including removal of softly/weakly referenced objects.
When the stack trace is present for this particular OOME, it is usually irrelevant – the specific allocation that could not be satisfied gives us no clue regarding previous allocations that probably caused the problem. Same with the thread where the error occured - It may occur in any thread, since they all share the same heap.
java.lang.OutOfMemoryError: PermGen space
When the permanent generation becomes full, this error occurs, regardless of the available space in the object allocation area (young + old generations).

This kind of OOME occurs in practice:
Applications which load classes dynamically, such as web servers and application containers
A class loader with a memory leak
Applications that make use of string interning, in order to improve performance or reduce heap usage
java.lang.OutOfMemoryError: unable to create new native thread
Whenever we start a a  thread in Java, the JVM allocates space in native memory, designated for the thread’s call stack. This space is freed only after the thread is terminated. In case that there is not enough native memory for the stack space, we get this error.

This error is common in applications that try to manage too many live threads, For example, an application that creates a thread per connection has a scalability problem in its design. - Try to use NIO to reduce dramatically the number of threads.

When OOM occurs, usually we should check our code to detect memory leak, or reconsider application design.
We can generate java heap dump, then use IBM Heap Analyzer or Eclipse Memory Analyzer to analyze the generated heap dump.

Useful JVM flags
Use -Xms and -Xmx to set the initial and maximal heap size

-XX:+HeapDumpOnOutOfMemoryError
Output details about garbage collection
-verbose:gc and -XX:+PrintGCDetails
Track the loading/unloading of classes
-XX:+TraceClassLoading(or -verbose:class)
and -XX:+TraceClassUnloading

-Xnoclassgc would prevent GC on classes, and can easily cause this OOME in applications that keep loading classes dynamically.
Increase the maximal size of the permanent generation
-XX:MaxPermSize=512m
Modify the size of memory allocated per stack using -Xss (e.g. -Xss512k).

Other cool articles about OOM
How are Java Strings stored?
When allocating a new string, the char array contains exactly the string content. Offset is set to 0, and count is set to the char array length. Then, when calling the method substring(..) upon it, the new string being returned contains a reference to the same char array, but its offset and count members are modified, reflecting the requested subsequence of chars. The sharing of the same char array by multiple String instances is possible, since strings are immutable. There are two benefits of this implementation approach in comparison to a substring implementation based on copying:
1) Memory usage is usually reduced, especially in cases where many substrings of the same string are taken, or if the substrings are long
2) substring(..) runs in constant time, instead of linear time

Whenever we know that the original string we take the substring from has a shorter life span than the substring itself, we should consider using the copy constructor to avoid sharing of the underlying char array.

Error reported: JVMCI015:OutOfMemoryError, cannot create anymore threads due to memory or resource constraints.
The message is what is known as a native out of memeory. This is when you have hit the limits of the address space for your an application under the OS.
First Question:- How many threads are you trying to create?
Second Question:- Do you have a high rate of thread burn (do you create a lot of short lived threads)?
Common causes of this kind of OOME:
* Java heap size is set too large which robs the system of memory
* Many short lived threads are created. Each of these will take up native heap space due to the space required for their stack.
* The system itself is just running out of space due to other programs which will prevent the
JVM from having enough space to expand the native heap (used for JIT compilation, JNI malloc and creating threads).
The JVM maintains two memory areas, the Java heap and the native (or system) heap. These two heaps have different purposes and are maintained by different mechanisms.
The Java heap contains the instances of Java objects and is maintained by Garbage Collection.
The maximum size of the Java heap is preallocated during JVM startup as one contiguous area.

The native, or system heap, is allocated by using the underlying malloc and free mechanisms of the operating system, and is used for the underlying implementation of particular Java objects; for example:
* Motif objects required by AWT and Swing
* Buffers for data compression routines, which are the memory space that the Java Class Libraries require to read or write compressed data like .zip or .jar files.
* Malloc allocations by application JNI code
* Compiled code generated by the Just In Time (JIT) Compiler
* Threads to map to Java threads

Resources:

Labels

Java (159) Lucene-Solr (110) Interview (59) All (58) J2SE (53) Algorithm (45) Soft Skills (36) Eclipse (34) Code Example (31) Linux (24) JavaScript (23) Spring (22) Windows (22) Web Development (20) Nutch2 (18) Tools (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) Troubleshooting (9) UIMA (9) html (9) Http Client (8) Maven (8) Security (8) bat (8) blogger (8) Big Data (7) Continuous Integration (7) Google (7) Guava (7) JSON (7) Problem Solving (7) ANT (6) Coding Skills (6) Database (6) Dynamic Languages (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) IDE (5) Lesson Learned (5) Programmer Skills (5) System Design (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Firefox (2) Google Drive (2) Gson (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Python (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts