Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, May 2, 2015

Java String

http://javaconceptoftheday.com/tutorial-examples-strings-in-java/

Time taken by String class : 429 ms
Time taken by StringBuffer class : 2 ms
Time taken by StringBuilder class : 0 ms

Therefore, when you are performing lots of string concatenation in your application, it is better to use StringBuffer class (if you need thread safety) or StringBuilder class (If you don’t need thread safety).
Time taken by String class : 429 ms
Time taken by StringBuffer class : 2 ms
Time taken by StringBuilder class : 0 ms
Therefore, when you are performing lots of string concatenation in your application, it is better to use StringBuffer class (if you need thread safety) or StringBuilder class (If you don’t need thread safety).
- See more at: http://javaconceptoftheday.com/stringbuffer-stringbuilder-string-class/#sthash.jQ0l5vUm.dpuf
Time taken by String class : 429 ms
Time taken by StringBuffer class : 2 ms
Time taken by StringBuilder class : 0 ms
Therefore, when you are performing lots of string concatenation in your application, it is better to use StringBuffer class (if you need thread safety) or StringBuilder class (If you don’t need thread safety).
- See more at: http://javaconceptoftheday.com/stringbuffer-stringbuilder-string-class/#sthash.jQ0l5vUm.dpuf
Time taken by String class : 429 ms
Time taken by StringBuffer class : 2 ms
Time taken by StringBuilder class : 0 ms
Therefore, when you are performing lots of string concatenation in your application, it is better to use StringBuffer class (if you need thread safety) or StringBuilder class (If you don’t need thread safety).
- See more at: http://javaconceptoftheday.com/stringbuffer-stringbuilder-string-class/#sthash.jQ0l5vUm.dpuf

Monday, July 28, 2014

Java/Scala benchmark and tools

http://shipilev.net/blog/2014/java-scala-divided-we-fail/
http://openjdk.java.net/projects/code-tools/jmh/
http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/

As a good tradition, we will take some diversions into benchmarking methodology, so that even though the post itself is targeted to platform people, the non-platform people can still learn a few tricks. As usual, if you still haven’t learned about JMH and/or haven’t looked through the JMH samples, then I suggest you do that first before reading the rest of this post for the best experience.

Benchmark

The discussion in that particular StackOverflow thread dates back a few questions, so instead of digging there, we will just take the latest benchmark code, and wrap it up with JMH. JMH already has the bindings for Java and Scala, which somewhat alleviates the difference in testing methodology. You can find full benchmark code here (warning, it contains spoilers).

Saturday, January 12, 2013

Spring Configuration Options: XML vs. Annotations

http://www.theserverside.com/tip/How-the-Java-Config-Module-Pounced-on-Spring-30

Spring Configuration Options: XML vs. Annotations
The XML camp talks about separation of concerns. XML configuration is outside the classes. The whole configuration can be viewed easily in only a few files. Furthermore, configuration can change without recompiling, etc.
Cons of XML could be that we have all these String values that need to be converted. Typos occur all over the place, they are difficult to debug, and they are not type safe because of the Strings.
The Annotations party, like myself, like the type safety of annotations. It can also self document a class, so that you can look in the class and truly see what is being injected by Spring.
The cons of Annotations is that it clutters the POJO, sometimes where you might say it is not a POJO anymore. If you change, add or delete, annotations require a recompilation and deployment.
So, who wins the debate?
Guess what: they are all correct. There is no best answer to this debate. So wouldn't it be great if we could get the 'pro' benefits of both styles and remove the cons.
With @Configuration, we can do just that.
@Configuration is configuration using Java classes. Each @Configuration Java class is its own configuration. Since it is Java, it is type safe, we can keep it as a POJO (with just a couple of annotations, we promise not too much), and we can have a clean separation of concerns. We will also have a single resource representing the application's configuration, and we can change it without having to change our application code.

Sunday, July 22, 2012

Java Classloaders



The Java platform ships with a number of typical classloaders, which are used to do different jobs during the startup and normal operation of the platform:

Primordial (or bootstrap) classloaderThis is instantiated very early in the process of starting up the VM, and is usually implemented as native code. It’s often best to think of it as being a part of the VM itself. It’s typically used to get the basic system JARs—basically rt.jar—loaded and it does no verification.


Extension classloader—This is used to load installation-wide standard extensions. This often includes security extensions.

Application (or system) classloader—This is the most widely used classloader. It’s the one that will load the application classes and do the majority of the work in in most SE environments.


Custom classloader—In more complex environments, such as EE or the more sophisticated SE frameworks, there will often be a number of additional (a.k.a. custom) classloaders. Some teams even write classloaders that are specific to their individual applications. In addition to their core role, classloaders are also often used to load resources (files that aren’t classes, such as images or config files) from JAR files or other locations on the classpath.

Wednesday, April 4, 2012

Application errors notification with Logback

http://maciejwalkowiak.pl/blog/2012/04/03/application-errors-notification-with-logback/

Logback in conjunction with SLF4J provides great API and fast and powerful implementation of logging framework. Reasons why to switch to Logback from log4j are not topic of this post and they are already described in details on logback website.

Thanks to SLF4J migration tool migration from log4j api to SLF4J is super fast. I’ve decided to switch all projects to Logback and after several months I have to say that I am really satisfied with that decision.

Friday, February 3, 2012

Moving from Scala to Java ... :(

http://www.infoq.com/news/2011/11/yammer-scala

An e-mail, sent from Yammer employee Coda Hale to Scala's commercial management at Typesafe, ended up being leaked via YCombinator and a gist at GitHub. The e-mail confirms that Yammer is moving its basic infrastructure stack from Scala back to Java, owing to issues with complexity and performance.

Yammer PR Shelley Risk confirmed to InfoQ that the e-mail represented the personal opinions of Coda Hale, rather than an official statement from Yammer itself; a follow up from the original author has been published at http://codahale.com/the-rest-of-the-story/. In it, Coda clarified that the message was a result of a request for feedback from Donald Fischer (CEO of Typesafe) following an earlier tweet indicating the move.

Update: Code has published Yammer's official position on the subject; which confirms the above points. It also points out that any language has flaws (not just Scala) and that the e-mail was an attempt at offering advice for how to improve Scala's performance and other concerns. Finally, it concluded that when rolling out any high performance project (for which Scala is their production environment) there are rough edges which need to be filed down; the e-mail was an attempt at helping Scala improve.

Wednesday, December 28, 2011

Comparable vs. Comparator

http://grdurand.com/static/presentation_four/comparable.html

Classes should implement the Comparable interface to control their natural ordering.

Objects that implement Comparable can be sorted by Collections.sort() and Arrays.sort() and can be used as keys in a sorted map or elements in a sorted set without the need to specify aComparator.

« Interface »
Comparable
+ compareTo(Object) : int
compareTo() compares this object with another object and returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the other object.

Use Comparator to sort objects in an order other than their natural ordering.

« Interface »
Comparator
+ compare(Object, Object) : int
+ equals(Object) : boolean
compare() compares its two arguments for order, and returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Monday, October 24, 2011

Java Swing MVC

It is said that the MVC in SWING is really MV/C. What this means it that most SWING components (Views) are pre-coupled with a default Model. The programmer only needs to add a Controller (EventListener) to it, to get it to a workable state.

While this is true for most cases, but usually only for simpler components, like JButton etc. The more complex components, like JTable, JTree or JList, require you to provide them with your own custom Model to get them to a fully functional state.

Reference: http://compsci.ca/v3/viewtopic.php?t=11199

Thursday, December 9, 2010

How to find the locking order for equals() ?

Always lock them in the same order, one way you could decide the order is on the results of System.identityHashCode(Object)

References:
http://stackoverflow.com/questions/1636399/correctly-synchronizing-equals-in-java
http://download.oracle.com/javase/tutorial/essential/concurrency/atomic.html


Never abruptly exit a finally block

Every finally block should complete normally, barring an unchecked exception.
Never exit a finally block with a return, break, continue, or throw, and never allow a checked exception to propagate our of a finally block.
When both try block and the finally block complete abruptly, the reason for the abrupt completion in the try block is discarded. Discarding the reason for abrupt completion is almost never what you want ... (Java Puzzlers p.78)


References:
http://accu.org/index.php/journals/236 (handle checked exception in finally block)
http://www.javamex.com/tutorials/exceptions/exceptions_finally.shtml
http://www.javamex.com/tutorials/exceptions/exceptions_hierarchy.shtml

Wednesday, December 8, 2010

Java volatile vs. synchronized

If volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory.

volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

volatile:
- Get a global lock on the variable
- Update the one variable from main memory
- Write any change of the one variable back to main memory
- Release the lock

synchronized:
- Get a global lock on the monitor
- Update all shared variables that have been accessed from main memory
- Process some statements
- Write all shared variables that have been changed back to main memory
- Release the lock


reference: http://www.javaperformancetuning.com/news/qotm051.shtml

Thursday, November 18, 2010

Java / Ektorp / CouchDB

Ektorp is a persistence API that uses CouchDB as storage engine. The goal of Ektorp is to combine JPA like functionality with the simplicity and flexibility that CouchDB provides ... more ...

Below is an example that I used to access my CouchDB and I ran the command curl --user user:password -X PUT http://my.couchone.com:5984/testdb/ektorp -d '{ "color": "red" }' first to create a document 'ektorp' before executing Java code.


import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.ektorp.support.CouchDbDocument;

public class Ektorp {
public static void main(String[] args) {
HttpClient httpClient = new StdHttpClient.Builder()
.host("my.couchone.com")
.port(5984)
.username("user")
.password("password")
.build();

CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
CouchDbConnector db = new StdCouchDbConnector("testdb", dbInstance);

db.createDatabaseIfNotExists();
Sofa sofa = db.get(Sofa.class, "ektorp");

if (sofa.getColor().equals("red")) {
sofa.setColor("green");
} else {
sofa.setColor("red");
}
db.update(sofa);
}
}

class Sofa extends CouchDbDocument {
private String color;
public void setColor(String s) {
color = s;
}

public String getColor() {
return color;
}
}

More examples here ...

Wednesday, November 17, 2010

Groovy / REST / CouchDB

The codes below from REST up with CouchDB and Groovy's RESTClient was modified to use login authentication based on this link ...

import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON

@Grab(group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '[0.5.0,0.5.1)')
def getRESTClient(local = false) {
RESTClient client;

if (!local) {
client = new RESTClient("http://my.couchone.com:5498/")
} else {
client = new RESTClient("http://my.couchone.com:5984/")
}

def authHash = "user:password".getBytes('iso-8859-1').encodeBase64()
client.headers.Authorization = "Basic $authHash"

return client;
}

def client = getRESTClient(true)

try {
client.get(path: "parking_tickets")
println "Deleting DB parking_tickets ..."
client.delete(path: "parking_tickets")
} catch (Exception e) {
println "Creating new DB parking_tickets ..."
}

def response = client.put(path: "parking_tickets", requestContentType: JSON, contentType: JSON)

assert response.data.ok : "response from server wasn't ok"

Note: Grab will download required jars to C:\Users\userName\.groovy\grapes\org.codehaus.groovy.modules.http-builder

Saturday, October 9, 2010

Disabled JSplitPane causes the resize cursor not working in JTable

I just found that whenever I disable a JSplitPane with setEnabled(false) then all the JTable in the pane will stop showing the resize cursor on the table header even though they are still resizable. So if you have to disable JSplitPane (make it not resizable) but still want the JTable in it be resizable then you need to provide your own resizer as below and apply it to your JTable this way new TableHeaderCursorResizer(jTable);



Monday, February 22, 2010

How to copy a file

How to copy a file

In Java 5 and 6:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
....
String orig ="file.xml";
String dest = "file.xml.bak";
InputStream in = new FileInputStream(orig);
OutputStream out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();

In Java 7:
import java.file.io;
import org.apache.commons.io.FileUtils;
....
String orig ="file.xml";
String dest = "file.xml.bak";
File fOrig = new File(orig);
File fDest = new File(dest);
FileUtils.copyFile(fOrig, fDest);

In Groovy:
new File("/tmp/otherFile") << new File("/tmp/someFile").text
( new AntBuilder ( ) ).copy ( file : 'blah' , tofile : 'fobar' )

Reference