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