To round x postion of decimal point, use BigDecimal.setScale().

double requestPerSecond = httpInfo.getRequestPerSencond();
BigDecimal reqPerSec =
     new BigDecimal(requestPerSecond).setScale(2,java.math.BigDecimal.ROUND_HALF_UP);

setScale

public BigDecimal setScale(int scale,
                           int roundingMode)
Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value. If the scale is reduced by the operation, the unscaled value must be divided (rather than multiplied), and the value may be changed; in this case, the specified rounding mode is applied to the division.

Note that since BigDecimal objects are immutable, calls of this method do not result in the original object being modified, contrary to the usual convention of having methods named setX mutate field X. Instead, setScale returns an object with the proper scale; the returned object may or may not be newly allocated.

Parameters:
scale - scale of the BigDecimal value to be returned.
roundingMode - The rounding mode to apply.
Returns:
a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.
Throws:
ArithmeticException - scale is negative, or roundingMode==ROUND_UNNECESSARY and the specified scaling operation would require rounding.
IllegalArgumentException - roundingMode does not represent a valid rounding mode.

'java core' 카테고리의 다른 글

JMX reference  (0) 2009.04.29
Effective Java Reload  (0) 2009.04.29
How to get cpu usage in java.  (0) 2009.04.29
How to get hostname in http url in Java  (0) 2009.04.28
G1 garbage collection  (0) 2009.04.28
Posted by '김용환'
,


Getting cpu usage in java instance, that limits in executing java virtual machine, not os.


Have a look at the java class sun.tools.jconsole.SummaryTab.java in open JDK7 or source in web.(http://www.docjar.com/html/api/sun/tools/jconsole/SummaryTab$Result.java.html)

If you know JConsole, you know that cpu usages graph. that source is below.

  354       private static class CPUOverviewPanel extends OverviewPanel {
  355           private long prevUpTime, prevProcessCpuTime;
  356   
  357           CPUOverviewPanel() {
  358               super(getText("CPU Usage"), cpuUsageKey, cpuUsageName, Plotter.Unit.PERCENT);
  359               getPlotter().setDecimals(CPU_DECIMALS);
  360           }
  361   
  362           public void updateCPUInfo(Result result) {
  363               if (prevUpTime > 0L && result.upTime > prevUpTime) {
  364                   // elapsedCpu is in ns and elapsedTime is in ms.
  365                   long elapsedCpu = result.processCpuTime - prevProcessCpuTime;
  366                   long elapsedTime = result.upTime - prevUpTime;
  367                   // cpuUsage could go higher than 100% because elapsedTime
  368                   // and elapsedCpu are not fetched simultaneously. Limit to
  369                   // 99% to avoid Plotter showing a scale from 0% to 200%.
  370                   float cpuUsage =
  371                       Math.min(99F,
  372                                elapsedCpu / (elapsedTime * 10000F * result.nCPUs));
  373   
  374                   getPlotter().addValues(result.timeStamp,
  375                                   Math.round(cpuUsage * Math.pow(10.0, CPU_DECIMALS)));
  376                   getInfoLabel().setText(getText(cpuUsageFormat,
  377                                                  String.format("%."+CPU_DECIMALS+"f", cpuUsage)));
  378               }
  379               this.prevUpTime = result.upTime;
  380               this.prevProcessCpuTime = result.processCpuTime;
  381           }
  382       }



So. I made my own class to get java-cpu usage.
private void _getJavaRuntime() {
OperatingSystemMXBean osbean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
RuntimeMXBean runbean = (RuntimeMXBean) ManagementFactory.getRuntimeMXBean();
int nCPUs = osbean.getAvailableProcessors();
long prevUpTime = runbean.getUptime();
long prevProcessCpuTime = osbean.getProcessCpuTime();
try {
Thread.sleep(500);
} catch (Exception e) { }
osbean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long upTime = runbean.getUptime();
long processCpuTime = osbean.getProcessCpuTime();
if (prevUpTime > 0L && upTime > prevUpTime) {
long elapsedCpu = processCpuTime - prevProcessCpuTime;
long elapsedTime = upTime - prevUpTime;
javacpu = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * nCPUs));
} else {
javacpu = 0.001;
}
uptime = runbean.getUptime(); 
}


'java core' 카테고리의 다른 글

Effective Java Reload  (0) 2009.04.29
Rounding(Scaling) x postion of decimal point  (0) 2009.04.29
How to get hostname in http url in Java  (0) 2009.04.28
G1 garbage collection  (0) 2009.04.28
Implementing equals method of collections classes  (0) 2009.04.27
Posted by '김용환'
,

I have a need to get hostname in httpd url. So. I made it simple by using pattern and matcher class.


public class Util {
public synchronized static String getHost(String domainURL) {
String host = new String();
Pattern pattern = Pattern.compile("(http://)+(\\w++-?\\w++)|(\\w++).?(\\w++.)++(\\w++)");
Matcher match = pattern.matcher(domainURL);
while (match.find()) {
String dashContained = match.group(2);
if (dashContained != null) {
host = match.group(2);
} else {
host = match.group(3);
}
}
return host;
}
}




public class GettingHostTest {
@Test
public void getHost() {
String url = "http://gmail.google.com"; // fulll domain
String host = MonitorUtil.getHost(url);
Assert.assertEndsWith("gmail", host);
}
@Test
public void getHost1() {
String url = "http://gmail1568h125.svr.google.com"; // sub domain
String host = MonitorUtil.getHost(url);
Assert.assertEndsWith("gmail1568h125", host);
}
@Test
public void getHost2() throws Exception {
String url = "http://alpha-gmail.google.com"; // dash contained domain
String host = MonitorUtil.getHost(url);
Assert.assertEndsWith("alpha-gmail", host);
}
}


'java core' 카테고리의 다른 글

Rounding(Scaling) x postion of decimal point  (0) 2009.04.29
How to get cpu usage in java.  (0) 2009.04.29
G1 garbage collection  (0) 2009.04.28
Implementing equals method of collections classes  (0) 2009.04.27
JavaOne 2008  (0) 2009.04.17
Posted by '김용환'
,

G1 garbage collection

java core 2009. 4. 28. 14:52

G1 ( Garbage First garbage collector) will be applied to jdk 1.6 update 14. It's target is to replace CMS gc algorithm that have no compaction. G1 lower latency time In large memory and is more predictable and enable fast allocation with memory. Compared to CMS, there are enhancedments like compacting,  Improved ease-of-use, predictability.
And It will give the merit that decrease the latency at most during gc time than CMS gc algorithm. Though its alogorithm, java application need fast response like web application have good performance.

Still default gc algorithm is parallel collector in jdk 1.6 update 14. After releasing, maybe used belows
 -XX:+UseG1GC

Actually G1 is introduced in java one 2008 (http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-5419&yr=2008&track=javase)


Looking for G1
- It aims Soft real-time scheduling.
- Compaction
 Disadvantages of CMS is compaction of old generation. CMS have no ability to compact thos generation. G1 have battles fragmentation that have no free lists
- Managin GC
Young gen split into regions to manage. Most reclamation (compaction) happens with evacuation pauses
By maintaining "remembered sets" to pick any region to collect
- GC time
Pause times in G1 quite higher than CMS. It means stop-the-world pause times is long and gc overhead.

Comparation between CMS and G1
CMS (Concurrent Mark & Sweep)
Concurrent threads move objects from young gen to old gen, search objects in object tree of old gen, mark dead object and deallocate marked dead objects continuously, not in full gc time.
- G1 Collector
Not devide into generational space, separate the a bunch of memory block, called region.
The objects in the region are managed by "remembered lists" which confirm referenece. 
And there in region, after checking if live objects are live or not, if region is filled up fully, all lived objects tranfered (copying and deallocating)to other regions. By transfering, fragementation problem can be solved.

https://jdk6.dev.java.net/6uNea.html
* GarbageFirst Garbage Collection David Detlefs, Christine Flood, Steve Heller, Tony Printezis Sun Microsystems, Inc. 1 Network Drive, Burlington, MA 01803, USA





'java core' 카테고리의 다른 글

How to get cpu usage in java.  (0) 2009.04.29
How to get hostname in http url in Java  (0) 2009.04.28
Implementing equals method of collections classes  (0) 2009.04.27
JavaOne 2008  (0) 2009.04.17
addShutdownHook() of Runtime class  (0) 2009.04.17
Posted by '김용환'
,

Let us supposed to have ArrayList<Your own class>, to sort, binary search, remove you need to know equal. This is connected to implement equals method of Object.
Just you have implement equals, it is very easy to manipulate Collections. Internally in Collections classes, there are many usage of equals methods.




public class MetaConnectionData {
private String project;

private String subDomain;

private String port;

public MetaConnectionData(String _project, String _subDomain, String _port) {
this.project = _project;
this.subDomain = _subDomain;
this.port = _port;
}

public String getProject() {
return project;
}

public void setProject(String project) {
this.project = project;
}

public String getSubDomain() {
return subDomain;
}

public void setSubDomain(String subDomain) {
this.subDomain = subDomain;
}

public String getPort() {
return port;
}

public void setPort(String port) {
this.port = port;
}

public boolean equals(final Object other) {
if (this == other) {
return true;
} else if ((other != null) && (other.getClass() == getClass())) {
final MetaConnectionData otherData = (MetaConnectionData) other; 
if (otherData.getPort().equals(port) 
&& otherData.getProject().equals(project)
&& otherData.getSubDomain().equals(subDomain)) {
   return true;
}
}
return false;
}
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
public int hashCode()  {    
return toString().hashCode();  
}
}



'java core' 카테고리의 다른 글

How to get hostname in http url in Java  (0) 2009.04.28
G1 garbage collection  (0) 2009.04.28
JavaOne 2008  (0) 2009.04.17
addShutdownHook() of Runtime class  (0) 2009.04.17
JDK7에 clossloader의 close 메소드가 생기다니.  (0) 2009.04.09
Posted by '김용환'
,

JavaOne 2008

java core 2009. 4. 17. 21:57

To study or listen the sessions of java one 2008, visit "http://developers.sun.com/learning/javaoneonline/j1online.jsp?track=coolstuff&yr=2008" web site.

You may be requested to login by sun.com. If you are sdn's member, you can access and enjoy it.

Also, you can visit this site. "http://java.sun.com/javaone/sf/sessions/general/index.jsp"

Posted by '김용환'
,


The addShutdownHook method of Runtime class is vervy useful to invoke something before a application exit. In addition coding in JUnit, very useful. 
If you create and use some Threads,  you can not invoke directly, this method usage is very helpful. 


public class Monitor {
private static Log log = LogFactory.getLog(HTMLPageFetcher.class);

private static NotificationCollector notiCollector;
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
close();
}
});
}
public static void close() {
log.info("close application.!!");
notiCollector.stop();
}


...

Posted by '김용환'
,

출처 : 
http://blogs.sun.com/CoreJavaTechTips/entry/closing_a_urlclassloader
http://blog.sdnkorea.com/blog/770

자바의 클래스 로더의 약점은 바로 cloassloader였다. 이 녀석들이 클래스 파일을 읽어서 객체로 인스턴스화하고, null이 되어 garbagec collector에 의해서 gc되기 전까지는 이름은 같은데, 다른 인스턴스에 대해서 로딩을 할 때 문제가 생기는 문제가 있었다.

이를 해결하기 위해서는  즉 객체와 연결이 끝나게 하는 Kill 또는 Dispose, Disconnect 같은 것이 필요했는데. 다행히 이번 jdk7에서부터 추가된다고 한다. 전부 다는 아니지만. URLClassLoader에 의해서 지원한다고 하니 좋은 소식이다.
즉, URLClassLoader를 close메소드를 호출하여 null 로 하고, 또다른 URLClassLoader를 이용해서 다른 클래스 로딩을 할 수 있기 때문에. 훨씬 모듈 프로그래밍에 획기적인 개발이 되지 않을 까 싶다.

URL ClassLoader는 다음의 리소스들을 지원한다. 모듈 프로그래밍이 정말 편해지게 될 것이라 생각된다.
  • file: (loads from file-system directories)
  • jar: (loads from JAR files)
  • http: (loads from http servers)

샘플 소스가 이를 말해준다!!! 모듈 프로그래밍이 잼나겠다. 다만.. jdk을 쓰지 못하는 임베디드쪽 자바는 힘들뿐~~ 
       // foo.jar 모듈을 읽는다.
       URL url = new URL("file:foo.jar");
       URLClassLoader loader = new URLClassLoader (new URL[] {url});
       Class cl = Class.forName ("Foo", true, loader);
       Runnable foo = (Runnable) cl.newInstance();
       foo.run();
       loader.close ();

       // foo.jar gets updated somehow

       loader = new URLClassLoader (new URL[] {url});
       cl = Class.forName ("Foo", true, loader);
       foo = (Runnable) cl.newInstance();
       // run the new implementation of Foo
       foo.run();






'java core' 카테고리의 다른 글

JavaOne 2008  (0) 2009.04.17
addShutdownHook() of Runtime class  (0) 2009.04.17
JMX 에서 standardbean 사용 관련 Tip  (0) 2009.03.28
JMX를 통해서 cpu 정보 구하기  (0) 2009.03.25
Java Memory 이야기  (0) 2009.03.25
Posted by '김용환'
,
Standard mbean을 만들기 위해서는 inteface로 먼저 MBean을 만들고, 그 구현체에서 interface를 상속하고 구현을 하도록 가이드가 되어 있다.

'java core' 카테고리의 다른 글

addShutdownHook() of Runtime class  (0) 2009.04.17
JDK7에 clossloader의 close 메소드가 생기다니.  (0) 2009.04.09
JMX를 통해서 cpu 정보 구하기  (0) 2009.03.25
Java Memory 이야기  (0) 2009.03.25
svn과 연동 (svnkit)  (0) 2009.03.25
Posted by '김용환'
,
jmx를 이용하여 해당 jvm instance의 cpu usage를 측정하는 메소드는 다음과 같이 되어 있다.

private void _getJavaRuntime() {
OperatingSystemMXBean osbean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
RuntimeMXBean runbean = (RuntimeMXBean) ManagementFactory.getRuntimeMXBean();

long bfprocesstime = osbean.getProcessCpuTime();
long bfuptime = runbean.getUptime();
long ncpus = osbean.getAvailableProcessors();

for (int i = 0; i < 1000000; ++i) {
ncpus = osbean.getAvailableProcessors();
}

long afprocesstime = osbean.getProcessCpuTime();
long afuptime = runbean.getUptime();

float cal = (afprocesstime - bfprocesstime)
/ ((afuptime - bfuptime) * 10000f);

javacpu = Math.min(99f, cal);
uptime = runbean.getUptime(); 
}

'java core' 카테고리의 다른 글

JDK7에 clossloader의 close 메소드가 생기다니.  (0) 2009.04.09
JMX 에서 standardbean 사용 관련 Tip  (0) 2009.03.28
Java Memory 이야기  (0) 2009.03.25
svn과 연동 (svnkit)  (0) 2009.03.25
exception시 어떻게 되는가?  (0) 2009.03.05
Posted by '김용환'
,