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);
        }
    }
}

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)