Sie sind auf Seite 1von 6

2015 International Conference on Energy Systems and Applications (ICESA 2015)

Dr. D. Y. Patil Institute of Engineering and Technology, Pune, India 30 Oct - 01 Nov, 2015

Minimizing Impact on Java Virtual Machine via


JAVA Code Optimization
Vamsi Krishna Myalapalli, Sunitha Geloth
Open Text Corporation,
Mind Space IT Park, Hi-Tec City,
Hyderabad, India
{vamsikrishna.vasu, sunithasaini}@gmail.com

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

978-1-4673-6817-9/15/$31.00 ©2015 IEEE 19


5) Static Final Constants: Many of the Dynamic Compilers Memory footprint might be increased by Tagged Classes as
ensure constant folding optimization when constants appear as they are clutter the code with switches, tag field(s) and enums
static final. etc. For transmuting a tagged class into class hierarchy, define
6) Strings as literals: Strings should be created as literals abstract class holding an abstract method for individual
instead of creating Strings using the 'new' keyword. method in tagged class whose functionality depends on tag
7) Prevent Finalizers: The Finalizer(s) are un-predictable value.
and might cause portability problems and severe performance 17) Favor Static Member Classes over Nonstatic: The
hitches . We should not put real time code in Finalizers under relationship among a non-static member class instance & its
any cost. Do not rest on on a finalizer in updating critical encompassing instance is generated after the former is created;
persistent state. it can’t be altered afterwards. Since this association consumes
8) Over riding the method toString(): This practice helps a memory in non-static member class instance and takes time
lot when the programmer is dealing with collections. As a best for its creation Non static member classes should be deterred.
practice toString should return vital information of the object.
Generics #(18-23):
Classes and Interfaces # (9-17): 18) Deter Raw types in Code: Type safety is lost if we
9) Members and Classes Accessibility must be Curtailed: encourage raw types in code. On the other hand the rate of
This should be enforced as much as possible. Data members bugs will increase.
must be kept hidden i.e. private and access to those must be 19) Obliterate Unchecked Warnings: Getting rid of
allowed via public methods. This ensures encapsulation or unchecked warnings (ClassCastException) makes the code
information hiding. Classes holding public mutable fields will type safe.
not be thread-safe. 20) Favor Lists over Arrays (Generic): Generics remain
10) Implementing Functional Interface(s) via Lambda(s): invariant and Arrays remain covariant.
They let us define default behavior for an interface and refer to 21) Prefer Generic methods: Type safety is secured with
the method without executing them. They eliminate verbosity. generic methods similar to classes. Static utility methods serve
11) Mutability must kept to minimum: Immutable objects as best contenders to generify.
are thread safe and can be freely shared along with their 22) If API flexibility to be escalated, enforce Bounded
members. Inorder to ensure immutability make classes and Wild Cards: This allows additional flexibility to what
their members final. invariant typing could offer.
Immutability ensures easy to use, test and failure atomic. 23) Consider Typesafe Heterogeneous Containers: This
In addition, they do not need defensed copying or cloning. Ex: provides type safety for the parameters of the container.
Integer, String etc.
12) Inheritance vs. Composition: (Is-A) Inheritance Enums # (24-27):
makes code fragile and violates encapsulation. Rather than 24) Prefer Enums instead of Constants: Switch upon
extending current class, offer the new class a private field enum is best to augment external enum type by constant
which references an instance of current class (Composition precise behavior.
(Has-A)). 25) Prefer Instance Members over Ordinals: ordinal
13) Deter Abstract Classes over Interfaces: Interfaces method gives numeric location in enum.
force the class to define its own definition which implements 26) Use EnumMap instead of Ordinal Indexing: Since
it. Inheriting abstract classes may result in collateral harm to array isn’t compatible with generics code requires an
type hierarchy. Interfaces permit creating non-hierarchical unchecked casting. Also there exists probability for mistake in
type frameworks and are idyllic for developing mixins. calculating array indices with ordinal indexing. EnumMap
14) Prefer Simulated Multiple Inhheritance: The class adds typesafety of Map to array speed.
which implements interface could forward invocation(s) of 27) Emulating Extendable Enum(s) from Interface(s): We
interface functions to contained instance of private inner class can’t compose extensible enum, but we could emulate it via
which extends the skeleton implementation. SMI allows interface. Thus permitting end users to compose specific
inheriting multiple classes (easiest method for evolving an enum(s) which implement that interface.
abstract class instead of Interface).
After launching and implementing interface, it’s General #(28-33):
practically difficult to modify the application code, hence 28) Enforce Marker Interface(s) for defining type(s):
prefer SMI. Interfaces with no methods are Marker/Tagged Interfaces.
15) Utilize interface(s) solely for defining type(s): (Ex: Serializable). Marker interface(s) express a type which
Interface(s) must not be used for propagating constants. It’s a will be implemented by instance(s) of Marked class, allowing
poor utilization of Interface. us to catch blunders during compile time.
16) Choose Hierarchy of class over Tagged Classes: 29) Return Blank Collections or Arrays instead of
Tagged classes are longwinded, ineffective and fault prone. returning Nulls: This occasionally minimizes load on JVM.

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.

36. try { ... } V. COMPARATIVE READING


Catch(InferiorLevelException e) We rewrote the code and recognized the resource utilization
{ throw new SuperiorLevelException(...); } using JProfiler profiling tool and noticed that tuning and long-
term maintenance are ensured. Apart from profiling the code,
40. ExecutorService es = we also investigated the byte code (.class files) using de-
Executors . newSingleThreadExecutor (); compiler against source code. Comprehensively rate of bugs
//Now submit runnable to execute were reduced and security is enhanced apart from decreasing
es.execute ( runnable ); time and space complexities. Our analysis could serve as
// Now Terminating gracefully benchmark practices for JAVA programmers in the form of
es .shutdown(); White box testing tool for questing concealed bugs.

47. public final class Period { VI. CLOSING COMMENTS


private final Date begin, stop; JAVA tuning plays a key role in the programming
Period(Date begin, Date stop) microcosm, due to the reason that JAVA is used as front-end
{ programming language in numerous commercial application
this .begin = new Date ( begin.getTime() ); developments. Tuning brings out huge performance
this .stop = new Date ( stop.getTime() ); enhancement irrespective of the platform. Hardware tuning is
} concerned with upgrading existing hardware on the other hand
private static class SerializingProxy software-tuning concentrates on tuning programming
implements Serializable methodologies and practices.
{
private final Date begin, stop; REFERENCES
SerializingProxy(Period p) { [1] Vamsi Krishna Myalapalli and Sunitha Geloth, “High Performance
JAVA Programming”, IEEE International Conference on Pervasive
this .begin = p .begin; this .stop = p .stop; } Computing, Pune, India, January 2015.
private Object readResolve() { [2] Vamsi Krishna Myalapalli, Jaya Krishna Myalapalli and Pradeep Raj
return new Period ( begin , stop ); Savarapu, “High Performance C Programming”, IEEE International
// Public constructor used Conference on Pervasive Computing, Pune, India, January 2015.
} [3] Joshua Bloch, “Effective JAVA”, Edition 2, Addisson Wesley
Publishers, 2002.
49. public enum Boolean{ [4] Vamsi Krishna Myalapalli, Sunitha Geloth and Srinivas Karri, “An
Appraisal to Secure JAVA Programming”, International Journal of
TRUE(true), FALSE(false); Innovative Research in Science, Engineering and Technology, Volume
private Boolean(boolean decision) 4, Issue 9, September 2015.
{ this.decision = decision; } [5] Vamsi Krishna Myalapalli and Bhupati Lohit Ravi Teja, “High
private final boolean decision; Performance PL/SQL Programming”, IEEE International Conference on
Pervasive Computing, Pune, India, January 2015.
public boolean booleanDecision() { return value; }
[6] Vamsi Krishna Myalapalli and Pradeep Raj Savarapu, “High
public String toString() Performance SQL”, 11th IEEE International Conference on Emerging
{ return value ? "true" ; "false"; } } Trends in Innovation and Technology, December 2014, Pune, India.
[7] Paul Deitel, Harvery Deitel “JAVA How to Program”, 8th Edition 2010.
50. public enum SingletonPattern PHI Publications, ISBN: 978-81-203-3832-6.
{ INSTC; }
Instead of

24

Das könnte Ihnen auch gefallen