Friday, February 7, 2014

Java - Exception with Logger

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class ExceptionLog {

static void showExceptionLog(String className, String message,
StackTraceElement[] stackTraceElements, Logger logger,
int loggerDepth) {
int logCount;

if (stackTraceElements.length > loggerDepth) {
logCount = loggerDepth;
} else {
logCount = stackTraceElements.length;
}

logger.error("{}: {}", className, message);

for (int i = 1; i <= logCount; i++) {
logger.error(stackTraceElements[stackTraceElements.length - i]
.toString());
}
}
}

public class Test extends Thread {

final Logger logger = LoggerFactory.getLogger(Test.class);

public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
ExceptionLog.showExceptionLog(e.getClass().getName(),
e.getMessage(), e.getStackTrace(), logger, 10);

// TODO Auto-generated catch block
// e.printStackTrace();
}
}

public static void main(String[] args) {
Test test = new Test();

test.start();
test.interrupt();
}
}

Java - format

public class Test {

public static void main(String[] args) {
final int LOOP_COUNT = 100;
String a = "aaa", b = "bbb", c = "ccc";
long d = 1, e = 2, f = 3;
String data;

long startTime = System.nanoTime();

for (int i = 0; i < LOOP_COUNT; i++) {
data = a + " " + b + " " + c + " " + d + " " + e + " " + f;
}

long endTime = System.nanoTime();
double elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println(elaspedTime);

startTime = System.nanoTime();

for (int i = 0; i < LOOP_COUNT; i++) {
data = String.format("%s %s %s %d %d %d", a, b, c, d, e, f);
}

endTime = System.nanoTime();
elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println(elaspedTime);

startTime = System.nanoTime();

for (int i = 0; i < LOOP_COUNT; i++) {
System.out.print(a + " " + b + " " + c + " " + d + " " + e + " "
+ f);
}

endTime = System.nanoTime();
elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println();
System.out.println(elaspedTime);

startTime = System.nanoTime();

for (int i = 0; i < LOOP_COUNT; i++) {
System.out.format("%s %s %s %d %d %d", a, b, c, d, e, f);
}

endTime = System.nanoTime();
elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println();
System.out.println(elaspedTime);
}
}

Thursday, February 6, 2014

Java - synchronized

1. example 1

class Contribution {
private int amount; // check example 2

public synchronized void donate() { // check example 2
amount++;
}

public int getTotal() {
return amount;
}
}

class Contributor extends Thread {
private Contribution contribution;
private String name;

public Contributor(Contribution contribution, String name) {
this.contribution = contribution;
this.name = name;
}

public void run() {
for (int i = 0; i < 1000; i++) {
contribution.donate();
}

System.out.format("%s total = %d\n", name, contribution.getTotal());
}
}

public class Test {

public static void main(String[] args) {
final int CONTRIBUTOR_NO = 10;

Contributor[] contributors = new Contributor[CONTRIBUTOR_NO];
Contribution contribution = new Contribution(); // check example 2

for (int i = 0; i < CONTRIBUTOR_NO; i++) {
contributors[i] = new Contributor(contribution, String.valueOf(i));
contributors[i].start();
}
}
}

2. example 2

class Contribution {
private static int amount; // check example 1

public static synchronized void donate() { // check example 1
amount++;
}

public int getTotal() {
return amount;
}
}

class Contributor extends Thread {
private Contribution contribution;
private String name;

public Contributor(Contribution contribution, String name) {
this.contribution = contribution;
this.name = name;
}

public void run() {
for (int i = 0; i < 1000; i++) {
contribution.donate();
}

System.out.format("%s total = %d\n", name, contribution.getTotal());
}
}

public class Test {

public static void main(String[] args) {
final int CONTRIBUTOR_NO = 10;

Contributor[] contributors = new Contributor[CONTRIBUTOR_NO];

for (int i = 0; i < CONTRIBUTOR_NO; i++) {
Contribution contribution = new Contribution(); // check example 1
contributors[i] = new Contributor(contribution, String.valueOf(i));
contributors[i].start();
}
}
}

Java - Thread (while and interrupt)

class InfinitThread extends Thread {
int value = Integer.MIN_VALUE;
private boolean flag = true;

public void run() {
while (flag) {
value++;

if (value == Integer.MAX_VALUE) {
value = Integer.MIN_VALUE;

System.out.println("MAX_VALUE");
}
}
}

public void setFlag(boolean flag) {
this.flag = flag;
}
}

public class Test {

public static void main(String[] args) throws InterruptedException {
InfinitThread infinitThread = new InfinitThread();

infinitThread.start();
Thread.sleep(2000);

System.out
.format("isInterrupted = %s\n", infinitThread.isInterrupted());

infinitThread.interrupt();

System.out
.format("isInterrupted = %s\n", infinitThread.isInterrupted());

infinitThread.setFlag(false); // delete this line and try
}
}

Java - Thread (sleep, join, isAlive, interrupt)

public class Test extends Thread {

public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
Test test = new Test();

test.start();
try {
int count = 0;

while (count < 5) {

test.join(1000);

count++;
System.out.format("%d second(s) waited\n", count);
}

if (test.isAlive()) {
test.interrupt();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Java - Runnable and Thread

class RunnableImplements implements Runnable {

public void run() {
System.out.println("Runnable");
}
}

class ThreadExtends extends Thread {

public void run() {
System.out.println("Thread");
}
}

public class Test {

public static void main(String[] args) {
RunnableImplements runnableImplements = new RunnableImplements();
ThreadExtends threadExtends = new ThreadExtends();

new Thread(runnableImplements).start();
threadExtends.start();
}
}

Java - Watch

import static java.nio.file.StandardWatchEventKinds.*;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Date;
import java.util.List;

class DirWatcherThread extends Thread {
String dirPath;

public DirWatcherThread(String dirPath) {
this.dirPath = dirPath;
}

public void run() {
System.out.println("Directory Watcher is started");

dirWatcher();

System.out.println("Directory Watcher is ended");
}

public void dirWatcher() {
try {
Path dirP = Paths.get(dirPath);
WatchService watcher = FileSystems.getDefault().newWatchService();
WatchKey key;

dirP.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

for (int i = 0; i < 4; i++) {
key = watcher.take();

String watchedTime = new Date().toString();
List<WatchEvent<?>> eventList = key.pollEvents();

for (WatchEvent<?> event : eventList) {
Path name = (Path) event.context();

if (event.kind() == ENTRY_CREATE) {
System.out.println(name + " is created at "
+ watchedTime);
} else if (event.kind() == ENTRY_DELETE) {
System.out.println(name + " is deleted at "
+ watchedTime);
} else if (event.kind() == ENTRY_MODIFY) {
System.out.println(name + " is modified at "
+ watchedTime);
}
}

key.reset();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public class Test {

public static void main(String[] args) {
DirWatcherThread dirWT = new DirWatcherThread("D:\\Test");
dirWT.start();
}
}

Java - FileReader, FileReader with buffer, BufferedReader

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Test {

public static ArrayList<StringBuffer> readCharStream(String fileName)
throws IOException {
ArrayList<StringBuffer> list = new ArrayList<StringBuffer>();
FileReader fileReader = null;

try {
fileReader = new FileReader(fileName);

int data = 0;
StringBuffer stringBuffer = new StringBuffer();

while ((data = fileReader.read()) != -1) {
if (data == '\n' || data == '\r') {
list.add(stringBuffer);
stringBuffer = new StringBuffer();
} else {
stringBuffer.append((char) data);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileReader != null) {
fileReader.close();
}
}

return list;
}

public static String readCharStreamWithBuffer(String fileName)
throws IOException {
StringBuffer retVal = new StringBuffer();
FileReader fileReader = null;

try {
fileReader = new FileReader(fileName);

final int BUFFER_SIZE = 1024 * 1024;
char[] readBuffer = new char[BUFFER_SIZE];
int resultSize = 0;

while ((resultSize = fileReader.read(readBuffer)) != -1) {
if (resultSize == BUFFER_SIZE) {
retVal.append(readBuffer);
} else {
for (int i = 0; i < resultSize; i++) {
retVal.append(readBuffer[i]);
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileReader != null) {
fileReader.close();
}
}

return retVal.toString();
}

public static ArrayList<String> readBufferedReader(String fileName)
throws IOException {
ArrayList<String> list = new ArrayList<String>();
BufferedReader bufferedReader = null;

try {
bufferedReader = new BufferedReader(new FileReader(fileName));

String data;

while ((data = bufferedReader.readLine()) != null) {
list.add(data);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}

return list;
}

public static void main(String[] args) throws IOException {
final String fileName = "D:\\Test.java";

long startTime = System.nanoTime();

readCharStream(fileName);

long endTime = System.nanoTime();
double elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println(elaspedTime);

startTime = System.nanoTime();

readCharStreamWithBuffer(fileName);

endTime = System.nanoTime();
elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println(elaspedTime);

startTime = System.nanoTime();

readBufferedReader(fileName);

endTime = System.nanoTime();
elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println(elaspedTime);
}
}

Monday, February 3, 2014

Java - Reflection and instanceof

import java.math.BigDecimal;

public class Test {

public static void main(String[] args) {
final int LOOP_COUNT = 100;
String result;
Object src = new BigDecimal("7");

long startTime = System.nanoTime();

for (int i = 0; i < LOOP_COUNT; i++) {
if (src.getClass().getName().equals("java.math.BigDecimal")) {
result = "BigDecimal";
}
}

long endTime = System.nanoTime();
double elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println(elaspedTime);

startTime = System.nanoTime();

for (int i = 0; i < LOOP_COUNT; i++) {
if (src instanceof java.math.BigDecimal) {
result = "BigDecimal";
}
}

endTime = System.nanoTime();
elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println(elaspedTime);
}
}

Java - Class, Field, Method

1. DemoClass

package test;

public class DemoClass {

private String privateField;
String field;
protected String protectedField;
public String publicField;

public DemoClass() {
}

public DemoClass(String arg) {
}

public void publicMethod() throws java.io.IOException, Exception {
}

public String publicMethod(String s, int i) {
return "s=" + s + " i=" + i;
}

protected void protectedMethod() {
}

private void privateMethod() {
}

void method() {
}

public String publicRetMethod() {
return null;
}

public InnerClass getInnerClass() {
return new InnerClass();
}

public class InnerClass {

}
}

2. DemoTest

package test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class DemoTest {

public static void main(String[] args) {
DemoClass demoClass = new DemoClass();
DemoTest demoTest = new DemoTest();

demoTest.getClassInfos(demoClass);
}

public void getClassInfos(Object clazz) {
Class demoClass = clazz.getClass();

getClassInfo(demoClass);
getFieldInfos(demoClass);
getMethodInfos(demoClass);
}

public void getClassInfo(Class demoClass) {
String className = demoClass.getName();
String classCanonicalName = demoClass.getCanonicalName();
String classSimpleName = demoClass.getSimpleName();
String packageName = demoClass.getPackage().getName();
String toString = demoClass.toString();

System.out.println("Class Name: " + className);
System.out.println("Class Canonical Name: " + classCanonicalName);
System.out.println("Class Simple Name: " + classSimpleName);
System.out.println("Package Name: " + packageName);
System.out.println("toString: " + toString);
}

public void getFieldInfos(Class demoClass) {
Field[] declaredFields = demoClass.getDeclaredFields();
Field[] fields = demoClass.getFields();

System.out.println("==========");
System.out.println("Number of Declared Fields: "
+ declaredFields.length);
System.out.println("Number of Fields: " + fields.length);

for (Field field : declaredFields) {
getFieldInfo(field);
}

System.out.println("----------");

for (Field field : fields) {
getFieldInfo(field);
}
}

public void getFieldInfo(Field field) {
String fieldName = field.getName();
int modifier = field.getModifiers();
String modifierStr = Modifier.toString(modifier);
String type = field.getType().getSimpleName();

System.out.println(modifierStr + " " + type + " " + fieldName);
}

public void getMethodInfos(Class demoClass) {
Method[] declaredMethods = demoClass.getDeclaredMethods();
Method[] methods = demoClass.getMethods();

System.out.println("==========");
System.out.println("Number of Declared Methods: "
+ declaredMethods.length);
System.out.println("Number of Methods: " + methods.length);

for (Method method : declaredMethods) {
getMethodInfo(method);
}

System.out.println("----------");

for (Method method : methods) {
getMethodInfo(method);
}
}

public void getMethodInfo(Method method) {
String methodName = method.getName();
int modifier = method.getModifiers();
String modifierStr = Modifier.toString(modifier);
String returnType = method.getReturnType().getSimpleName();
Class params[] = method.getParameterTypes();
StringBuilder paramStr = new StringBuilder();
int paramLen = params.length;

if (paramLen != 0) {
paramStr.append("(").append(params[0].getSimpleName())
.append(" arg");

for (int i = 1; i < paramLen; i++) {
paramStr.append(", ").append(params[i].getName())
.append(" arg").append(i);
}

paramStr.append(")");
} else {
paramStr.append("()");
}

Class exceptions[] = method.getExceptionTypes();
StringBuilder exceptionStr = new StringBuilder();
int exceptionLen = exceptions.length;

if (exceptionLen != 0) {
exceptionStr.append("throws ")
.append(exceptions[0].getSimpleName());

for (int i = 1; i < exceptionLen; i++) {
exceptionStr.append(", ").append(exceptions[i].getSimpleName());
}
}

System.out.println(modifierStr + " " + returnType + " " + methodName
+ paramStr + " " + exceptionStr);
}
}