Friday, January 16, 2009

volatile keyword

Lock free, an alternative to synchronization and lock. A volatile variable is one whose value is always written to and read from "main memory" and not cached by register or thread. That means that different threads can access the variable.

A typical example of a "stop request" flag allowing one thread to signal to another to finish:


public class StoppableTask extends Thread {
private volatile boolean pleaseStop;
public void run() {
while (!pleaseStop) {
// do some stuff...
}

public void tellMeToStop() {
pleaseStop = true;
}
}

If the variable were not declared volatile (and without other synchronization), then it would be legal for the thread running the loop to cache the value of the variable at the start of the loop and never read it again.

See: The volatile keyword in Java 5

Tuesday, January 13, 2009

JVM GC



-Xloggc:[filename] is used to log GC. verbose:gc output to stdout.
-XX:+PrintGCDetails is to display more GC details on stdout.

There are two primary measures of garbage collection performance. Throughput is the percentage of total time not spent in garbage collection, considered over long periods of time. Throughput includes time spent in allocation (but tuning for speed of allocation is generally not needed.) Pauses are the times when an application appears unresponsive because garbage collection is occurring.

Reference:
[1] Java theory and practice: A brief history of garbage collection
[2] Java theory and practice: Garbage collection in the HotSpot JVM
[3] Tuning Garbage Collection with the 5.0 Java[tm] Virtual Machine

Friday, January 2, 2009

Mutablity


private MutableLocation loc = new MutableLocation();
public Location getLocation() {
return loc;
}

Internally, you store a mutable object, but return it typed as a simple interface when you want to allow only read-only access.This is done to preserve encapsulation and prevents the location fields from being modified by external code.

Wednesday, December 10, 2008

Java Utility Methods

1. Conversion
  a) Array => String

String modeStr = StringUtils.join(modes, '/')

  b) String => Array
String[] modes = StringUtils.split(protocolStr, '/')

2. Bit Ops
  a) Check bit
int RADIO_PROTOCOL_A = 0x1;
if (radioMode & RADIO_PROTOCOL_A) == RADIO_PROTOCOL_A

   b) Set/Unset bit
radioMode = radioMode | RADIO_PROTOCOL_A
radioMode = radioMode & ~RADIO_PROTOCOL_A