Minimizing Impact On JAVA Virtual Machine Via JAVA Code Optimization PDF
Minimizing Impact On JAVA Virtual Machine Via JAVA Code Optimization PDF
Dr. D. Y. Patil Institute of Engineering and Technology, Pune, India 30 Oct - 01 Nov, 2015
Abstract— In the contemporary programming microcosm techniques for reducing time and space complexity in plain
most of the commercial applications are contingent upon JAVA JAVA code and other best practices to minimize load levied
programming language as front end language and is escalating on the JVM.
exponentially. Performance engineering the code plays a crucial High Performance C Programming [2] explained tuning
part. Many JAVA programmers code programs with less
code via arithmetic logic, variable scope impact on the
contemplation towards optimized processing. Code tuning often
engenders massive performance enhancement. As such, the compiler and other associated issues.
proposed model is intended to bolster the JAVA programmers to When tuning an application, the bottlenecks have to be
enhance and tune the JAVA code dependent application(s). This recognized. For example, if our code is processor bound the
paper exposes sundry miscellaneous rewriting techniques for algorithms should be tuned and short-lived objects must be
escalating JAVA application program performance towards handled appropriately. Tuning bottlenecks is an incessant
minimizing impact on JVM and could oblige as an optimization process. Hence, critical ones must be handled accurately.
tool for JAVA application programmer(s). Our investigatory This paper explains the rewriting methodologies to reduce
denouements advocate that performance enhancements i.e. Space object utilization in plain JAVA code and in turn, this tuned
and Time complexities were enriched.
plain JAVA code can be employed with other miscellaneous
Keywords— JAVA Optimization; JAVA Tuning; JAVA Code code.
Rewrite; JAVA Performance Tuning; JAVA Code Tuning.
III. PROPOSED BENCHMARK
I. INTRODUCTION There exists sundry approaches for JAVA tuning and this
paper explains holistic techniques for JAVA tuning where we
Making programs run faster in a production environment is
a challenge for many developers. We can considerably optimize the JAVA application performance. We performed
enhance the performance of the Server & applications snooping upon resource utilization using JProfiler profiling tool
deployed on it by mutating some server configuration and and byte code using de-compiler software.
deployment settings.
Application developers should tune applications prior to Code Handling #(1-8):
usage in production. Application Tuning results in massive 1) Concatenate Strings using String Builder: ‘String’ is
performance improvements. Once the application tuning is immutable whereas ‘StringBuilder’ is mutable. Performance
complete System administrators carry out rest of the steps in enhances if ‘StringBuilder.append()’ is used instead of string
below list. concatenation. The latter case causes expensive copying &
Sequence of Steps for performance tuning: upshots significant performance degradation.
1. Application Tuning (The Proposed model). 2) Variables should be assigned null which are no Longer
2. Server Tuning. Required: This tactic assists the garbage collector to recognize
3. Java Run time System Tuning. the fragments of memory which can be securely reclaimed. It
4. Operating system Tuning. should be noticed that it JAVA will not thwart memory leaks
Further paper is prepared as follows. Second section and excess memory consumption.
explains the associated background and related work. Third
3) Detecting Memory Leaks: Profiling tools help
section deals with proposed benchmark i.e. the techniques.
programmers to detect memory leaks. Enforcing memory
Fourth section demonstrates experimental setup i.e.
snapshots after each transaction will also keep track of memory
implementing tactic. Section 5 explains comparative analysis
and finally section 6 concludes the paper. leaks. Leak free applications ensure active heap memory after
subsequent garbage collection(s).
II. BACKGROUND AND RELATED WORK 4) Moving to Final Methods on extreme necessity: The
High Performance JAVA Programming [1] explained ‘final’ keyword thwarts over riding. Some Dynamic compilers
sundry techniques to reduce time and space complexity in ensure ‘inter procedural optimization’ and ‘inlining’ if methods
commercial JAVA application code made of servlets, beans, are not final.
JDBC and other plain JAVA code. This paper encompasses
20
30) Favor for-each loop over while/for loop: For-Each 42) Notify vs notifyAll: Prefer notifyAll over notify to
hides iterator or index variable and marks the code ensue liveness for threads. This will not lead to abrupt issues.
uncluttered. 43) Focus on Lazy Initializing: This minimizes burden of
31) Favor Primitive type(s) over Boxed primitive(s): initializing class or creating instance, on escalating price of
Primitive (contains solely fully functional values) is usually accessing lately initialized field. We can initialize lazily to
less space and time complexive compared to that of boxed attain performance and to break risky initializing circularity.
primitive (contains 1 non-functional value). If primitve and 44) Never rely over Thread Scheduler: Though this
boxed primitive is mixed or program boxes primitive(s), it escalates performance, it makes our code non-portable and
results in creating needless and expensive objects. non robust. (Ex: yield and priority methods).
32) Prevent Strings if another type is suitable: String is 45) Favor Thread pool Executors over Thread Groups:
inappropriate alternative for enum, aggregate and primitive ‘Thread groups’ sequester applets for security. They doesn’t
type, since they are slower and not much flexible. provide efficient functionality and performance.
33) Reference Objects via their Interfaces: We must 46) Deal with Serializable meticulously: This minimizes
favor the use of interfaces rather than classes to refer to the elasticity in altering a class design after it is
objects. If applicable interface type is present, then variable(s), distributed/released apart from increasing testing burden and
parameter(s), return value(s), and fields must be declared by the certainity for bugs and security glitches.
interface type(s). This ensures flexibility for code. 47) Prefer Serialization Proxies over Serialized
Instances: Create static private inner class of serializable class
Exceptions # (34-37): which briefly signifies logical state of object of encompassing
34) Checked vs Unchecked (Runtime) Exception: We class. This inner class is serialization proxy ans minimizes
should enforce checked exception on condition to which glitches faced with Serializable clause.
invoker could practically recovered. On the other hand enforce
unchecked exception (subclassing RuntimeException) for Miscellaneous # (48-51):
indicating coding error. 48) Deal with Native methods meticulously: They are
35) Prevent Needless Checked Exception(s): More used for backward compatibility (C, C++) and for
checked exceptions will clutter the API. Runtime exceptions performance. This makes the code non-portable.
will perform fine when normal code cannot perform well. 49) Favor 2 element enum type over boolean type: This
36) Raising Exception Applicable to Abstraction: Raised offers the program R/W capability and allows auto-completion
exception should be relevant with code. If implementation at IDE.
high layer is changed, then with succeeding code, the 50) Implement Singleton Pattern wisely: Singleton makes
exception it throw would change, breaching current end user it tough to examine its clients, since it is not probable for
code. Prevention: Implement ‘Exception Translation’ i.e. High replace a mock design to singleton except if it is implementing
must catch low layer exception(s). ‘Exception Chaining’ could an interface which could serve as its type.
strengthen this process. 51) Enforce Defensed Copy over Mutable fileld(s):
37) Never Overlook Exceptions: Blank catch block beats Defense copying thwarts modification of mutable field(s).
the neccessity for an exception. On minimum, it must
comprise comment enlightening the reason for its presence.
IV. EXPERIMENTAL SETUP
Threads #(38-47): In this section, some of the tactics specified in immediate
38) Ensure Thread Safety: If various threads share data, earlier section are explained via queries aiming that they serve
every thread which writes or reads data should undergo as an exemplary. We have tested these code snippets for
synchronization. evaluating memory leaks, time and space complexity using
39) Evade Extreme Synchronization: Surplus sync drags JProfiler profiling tool.
down performance and may trigger deadlock. In synchronized
1. a) StringBuilder tmp = new StringBuilder("Hackers");
body don’t invoke method which could be overridden or
tmp.append("Galaxy");
offered from client in the form of method object (alien
tmp.append("Astronomy");
method). String str = tmp.toString();
40) Favor Tasks and Executors over Thread(s): Executor Instead of
is a malleable interface dependent execution feature for tasks. b) String strn = "Hackers";
Scheduled thread-pool executor will allow several threads and strn = strn + "Galaxy";
recover graciously from tasks which throw unchecked strn = strn + "Astronomy";
exception(s).
41) Favor Concurrency Utilities over notify and wait: The compiler translates the second case into following
Concurrency utilities of high level must be enforced, since String strn = "Hackers";
wait and notify will lock and decelerate code. StringBuilder tmp = new StringBuilder(strn);
21
tmp.append("Galaxy");
strn = tmp.toString(); 14. interface IPenguin { public void lay(); }
StringBulder tmp = new StringBuilder(strn); interface IKangaroo { public void spawn(); }
tmp.append("Astronomy"); class Penguin implements IPenguin {
strn = tmp.toString(); public void lay() { System.out.print("Laying"); }
}
2. Moon m = new Moon(); class Kangaroo implements IKangaroo {
// Code part that uses m public void spawn(){System.out.print("Spawning");}
m=null; // Now ‘m’ is qualified for Garbage collection }
System.gc(); class DuckBPlatypus implements IKangaroo, IPenguin {
Above statement is equivalent to private class LayingAnimal extends Penguin {}
Runtime.getRuntime().gc() private class SpawningAnimal extends Kangaroo {}
private LayingAnimal layingAnimal = new
6. String do = “Hard Work Never Fails”; LayingAnimal();
Instead of private SpawningAnimal spawningAnimal = new
String do = new String (“Hard Work Never Fails”); SpawningAnimal();
@Override
10. interface Roof public void lay() { layingAnimal.lay(); }
{ int makeInc(int g); } @Override
public class Home public void spawn() { spawningAnimal.spawn(); }
{ }
public static void main(String... z)
{ 15. class MyConstants
Roof r = (n) -> n+1; // Anonymous over ride {
System.out.print( r.makeInc(9) ); private MyConstants() { } // Prevents instantiation
} } static final double const1 = 76.76, const2 = 32.32;
Instead of }
interface Roof Instead of
{ int makeInc(int g); } interface MConstants
public class Home implements Roof { static final double const1 = 76.76;
{ static final double const2 = 32.32; }
public int makeInc(int g)
{ return g+1; } 16. class Polygon {
public static void main(String... z) enum Shape { SQUARE, OVAL };
{ final Shape shaped; // Tag field - Shape of this Polygon
System.out.print(new Home().makeInc(9)); double length, width; // fields used only for SQUARE
} } double rad; // fields used only for OVAL
Polygon(double rad)
12. class Profession { { shaped = Shape.OVAL; this.rad = rad; }
private int income; Polygon(double length, double width)
public int getIncome() { return income; } { shaped = Shape.SQUARE; this.length = length;
public void setIncome(int income) this.width = width;
{ this.income = income; } }
} double area() {
class Individual { switch(shaped) {
private Profession prof; case SQUARE: return length * width;
public Individual() case OVAL: return Math.PI * (rad * rad);
{ this.prof=new Profession(); prof.setIncome(1000); } default: throw new AssertionError();
public int getIncome() { return prof.getIncome(); } }
} }
public class CompoTest { }
public static void main(String... zz) {
Individual person = new Individual(); 17. class Out
System.out.print(person.getIncome()); {
} static class In
} { // Members }
// Individual Has-A Profession }
22
Instead of f.putFav (String.class, "Java");
Class Out f.putFav (Integer.class, 0xcafebabe);
{ f.putFav (Class.class, Favorites.class);
Class In String favStrn = f.getFav (String.class);
{ //Members } int favInt = f.getFav (Integer.class);
} Class<?> favClass = f.getFav (Class.class);
System.out.print("%s %x %s%n", favStrn,
19. Set<Apps> app = new HashSet<Apps>(); favInt, favClass.getName ());
Instead of
Set<Lark> app = new HashSet(); // Gives warning 24. enum Moons
{
20. Case 1: // Fails on compile, due to incompatibility EARTH(1), MARS(2), JUPITER(67), SATURN(62);
List<Object> xl = new ArrayList<Double> (); private int mooncount;
xl.add("can’t come now "); private Moons (int mooncount)
Case 2: // Runtime Failure (Bug in Code) { this.mooncount = mooncount; }
Object[] xl = new Long[2]; public int getmooncount() { return mooncount; }
xl[0]= “can’t come now"; // ArrayStoreException }
public class MoonTest {
21. static <E> Set<E> unite (Set<E> q1, Set<E> q2) { Moons moon;
Set<E> res = new HashSet<E> (q1); public MoonTest(Moons moon) { this.moon = moon; }
res.addAll(q2); }
return result; Moons.MARS.getmooncount(); // Invoking this returns 2
} Instead of
Instead of public static final int EARTH=1, MARS=2, JUPITER=67;
static Set unite (Set q1, Set q2) {
Set res = new HashSet (q1); 25. enum Moons { private int mooncount;
res.addAll(q2); EARTH(1), MARS(2), JUPITER(67);
return res; private Moons (int mooncount)
} { this.mooncount = mooncount; }
public int getmooncount() { return mooncount; } }
22. void addAll(Iterable<? extends E> source) { Instead of
for (E z : source) enum Moons { private int mooncount;
push(z); // Insert value to some store EARTH(1), MARS(2), JUPITER(67);
} private Moons(int mooncount)
Instead of { this.mooncount = mooncount; }
void addAll(Iterable<E> source) { public int getmooncount() { return ordinal()+1; } }
for (E z : source)
push(z); 26. public class Crop {
} public enum Type {BIENNIAL,ANNUAL,PERENNIAL}
In case 1, the method can accept any kind of number i.e. private final Type typ; private final String labl;
Integer, double etc, without compromising at type safety. Crop(String labl, Type typ)
{ this.labl = labl; this.typ = typ; }
23. class Fav { }
private Map<Class<?>, Object> favs = Then
new HashMap <Class<?>, Object> (); Map<Crop.Type, Set<Crop>> cropsByType =
public <T> void putFav (Class<T> typ, T instnc) new EnumMap<Crop.Type, Set<Crop>>(Crop.Type.class);
{ for (Crop.Type z : Crop.Type.values())
if (typ == null) cropsByType.put (z, new HashSet<Crop>());
throw new NullPointerException ("Invalid"); for (Crop c : garden)
favs.put ( typ, instnc ); cropsByType.get(c.typ).add(c);
} System.out.println(cropsByType);
public <T> T getFav (Class<T> typ) { Instead of
return type.cast ( favs.get (typ) ); Set<Crop>[] cropsByType =
} ( Set<Crop> []) new Set[Crop.Type.values().length];
} for (int z = 0; z < cropsByType.length; z++)
// The upcoming code goes into main() cropsByType[z] = new HashSet<Crop>();
Fav f = new Fav(); for(Crop c :garden) cropsByType[c.typ.ordinal()].add(c);
23
for (int z = 0; z < cropsByType.length; z++) public class SingletonPattern
System.out.printf("%s : %s %n", {
Crop.Type.values()[z], cropsByType[z]); public static final Elvis INSTC = new SingletonPattern ();
private SingletonPattern () { }
27. interface IMoons { public int getMoons(); } static SingletonPattern getInstc() { return INSTC; }
enum Moon implements IMoons { }
MARS { @Override public int getMoons() { return 2; }},
EARTH {@Override public int getMoons() { return 1; }}, 51. Date raiseDate; // Mutable field
JUPITER {@Override public int getMoons() {return 67;}}; public Date getraiseDate ()
public int getMoons() { return 1; } } { return new Date(getraiseDate.getTime()); }
Then statement Moon.MARS.getMoons() Gives 2 Instead of
public Date getraiseDate()
33. List<Moon> moons = new ArrayList<Moon> (); { return raiseDate; }
Instead of Now, even if returned object is modified, the genuine
ArrayList<Moon> moons = new ArrayList<Moon> (); one is stays unaffected.
24