If you are working with the multi-threaded programming, the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn't know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.
The model for event processing in version 1.0 of the AWT is based on inheritance. In order for a program to catch and process GUI events, it must subclass GUI components and override either action() or handleEvent() methods. Returning "true" from one of these methods consumes the event so it is not processed further; otherwise the event is propagated sequentially up the GUI hierarchy until either it is consumed or the root of the hierarchy is reached. The result of this model is that programs have essentially two choices for structuring their event-handling code:
Each individual component can be subclassed to specifically handle its target events. The result of this is a plethora of classes.
All events for an entire hierarchy (or subset thereof) can be handled by a particular container; the result is that the container's overridden action() or handleEvent() method must contain a complex conditional statement in order to process the events.
While the above model works fine for small applets with simple interfaces, it does not scale well for larger java programs for the following reasons:
The requirement to subclass a component in order make any real use of its functionality is cumbersome to developers; subclassing should be reserved for circumstances where components are being extended in some functional or visual way.
The inheritance model does not lend itself well to maintaining a clean separation between the application model and the GUI because application code must be integrated directly into the subclassed components at some level.
Since ALL event types are filtered through the same methods, the logic to process the different event types (and possibly the event targets in approach #2) is complex and error-prone. It is not uncommon for programs to have perplexing bugs that are the result of returning an incorrect result (true or false) from the handleEvent() method. This becomes an even greater problem as new event types are added to the AWT; if the logic of existing handleEvent() methods isn't set up to deal properly with unknown types, programs could potentially break in very unpredictable ways.
There is no filtering of events. Events are always delivered to components regardless of whether the components actually handle them or not. This is a general performance problem, particularly with high-frequency type events such as mouse moves.
For many components, the action() method passes a String parameter which is equivalent to either the label of the component (Button, MenuItem) or the item selected (List, Choice). For programs which use approach #2, this often leads to poor coding and unwieldy string-compare logic that doesn't localize well.
Continue: The continue statement is used in many programming languages such as C, C++, java etc. Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement. There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions.
In this program we will see that how the continue statement is used to stop the execution after that.
- no title specified
- no title specified- no title specified- no title specified- no title specified
If available, JNDI and the DataSource interface should be used to get a Connection instead of DriverManager. The JNDI style is typical when using an application server or a web container. (For example, the popular Tomcat product includes JNDI services and connection pools.)
Always remember that database connections need to be properly released!
Options for specifying the connection parameters include :
server configuration settings (likely the most common style)
direct user input for user name and password
a properties file, web.xml file, or ResourceBundle to keep parameters out of compiled code
String in a class it is used to holding the array of characters. The difference between String and StringBuffer is String is immutable where as StringBuffer is mutable. Means we can not change the value of the string.
Why it so?
Actually in java, Strings are handling in Pool format.
For example:
String str1 = “xyz”;
This string(str1) will be stored into memory in particular address. When we defining new String with same array of characters like
String str2 = “xyz”;
Now JVM will check in String Pool where there is same characters are available or not. If two Strings are match the JVM will refer str1 address to str2. Now the str1 and str2 referring the same characters in same memory location. This is a good idea for increasing memory efficiency. When we change the str1 characters, the changes will be reflected to str2. Because both str1 and str2 variables are referring the same memory location. For avoiding this we are keeping String as immutable. However we can use StringBuffer if you want to do modifications in the string.
Advantages of Immutablitiy
You can share immutable objects between threads without danger of changes confusing the other thread. You don’t need any locking. Two threads can both work on an immutable object at the same time without any possibility of conflict.
Once you check the value, you know it has to stay safe. No one can pass you a value, then behind your back swap it to an unsafe one using a background thread. This is particularly important in high security situations where allowing an invalid value to sneak in could compromise system integrity, e.g. a filename. This is probably the main reason that Strings are immutable.
You can share duplicates by pointing them to a single instance. You need only one copy, e.g. String interning. This saves RAM. With mutable StringBuilders that were temporarily identical, you could not throw one away, and replace it with a reference to the other, since at any moment their values could diverge again.
You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret behind Java’s very fast substring implementation.
Immutable objects are much better suited to be Hashtable keys. If you change the value of an object that is used as a hash table key without removing it and re-adding it you lose the mapping.
Since String is immutable, inside each String is a char[] exactly the correct length. Unlike a StringBuilder there is no need for padding to allow for growth.
Garbage Collection Techniques to Enhance Memory Locality in Java Programs
James Smith and Min Zhong
Java is a new popular object oriented programming language.Dynamic memory allocation is natural in object oriented programming language.Objects are created (have memory space allocated for them), at run time, used, then die (are no longer referenced and space no longer in use).A feature of Java is that memory is periodically "Garbage Collected" (GC) -- that is, memory space holding dead objects is re-claimed for use by newly created objects.High performance computers use memory hierarchies where objects accessed close together in time are also placed close together in memory. This property is a form of "locality", and good memory locality is critical for high performance.Dynamic memory allocation and GC often have negative effects on the placement of data in memory, and, therefore, the memory locality properties. We plan to study how the conventional memory allocation and GC schemes affect the system performance using a tool from Sun Microsystems (the original Java developers) that provides a dynamic trace of object activity as a program runs, and a software we will develop that models memory allocation/GC algorithms and memory hierarchy.By observing the performance trend and the objects’ characteristics, we can characterize the optimum performance for an ideal algorithm, and get an idea of how much performance improvement can be achieved.We will then be able to come up with some new memory allocation/GC algorithms that could enhance memory locality and improve the system performance.
Java is a new object oriented programming language that is coming into widespread use because it simplifies software development, is platform-independent, and contains built-in security features. Memory allocation in Java is dynamic in nature -- a large number of data objects are created, used, then die (are no longer referenced) throughout the execution of a Java program.
One attractive feature of Java is that the run time system (not the programmer) is responsible for all memory allocation and management.A key part of memory management is the use of automatic "Garbage Collection" (GC).That is, memory space holding dead objects is re-claimed for use by newly created objects without the need for any programmer intervention.
Dynamic memory allocation and garbage collection can have detrimental performance effects, however, because the placement of objects in memory can occur in a rather non-systematic, unpredictable way. In contrast, most computers are dependent on memory data placement for good performance. In particular, high performance computers use memory hierarchies which perform better when data (objects) accessed close together in time are also placed close together in memory -- this is a form of data "locality" that is exploited by cache memories and paged virtual memory systems.On modern systems, memories are organized in a hierarchy, from the top of the pyramid, the small and fast memory, to the bottom, the larger and slower memories, i.e. from caches, to the main memory, to the even slower hard disks.The smaller and expensive memory gives a processor fast data access, while the bottom of the pyramid provides cheap and large capacity at the cost of speed.Due to the limitedness of the amount of the physical resource at the higher end of hierarchy, organizing the placement of data in the fast memory, or preserving the memory locality is essential to high performance.
We plan to study the effects of memory allocation and GC on memory locality in Java programs and to propose new allocation/GC algorithms that will enhance data locality and increase overall system performance.
A number of GC algorithms have been proposed in the literature.A classical algorithm is “Reference Counting” [Collins, 1960], which maintains in each allocated block of memory the number of pointers pointing to that block.The block is freed when the count drops to zero.This algorithm degrades the user program's performance since it has to update the count upon every allocation and takes up space in each block to hold the count.The biggest flaw is that it doesn't detect cyclic garbage.
An often implemented classical algorithm is the "Mark and Sweep" algorithm [McCarthy, 1960].The algorithm traverses through the whole dynamic memory space, or heap, marks all the live objects, and then "sweeps" all the unmarked "garbage" back to the main memory.The algorithm handles cyclic pointer structures nicely.But once GC is started, it has to go through all the live objects non-stop in order to complete the marking phase.This could potentially slow down other processes significantly, and is probably not desirable in the case of real-time systems or where response time is important (this includes many Java applications). It bears a high cost since all objects have to be examined during the "sweep" phase -- the workload is proportional to the heap size instead of the number of the live objects.Also, data in a mark-swept heap tend to be more fragmented, which may lead to an increase in the size of the program's working set, poor locality and trigger more frequent cache misses and page faults for the virtual memory.
Another classic GC method is the copying algorithm [Minsky, 1963].The heap (storage where dynamic objects are kept) is divided into two sub-spaces: one containing active objects and the other "garbage".The collector copies all the data from one space to another and then reverses the roles of the two spaces.In the process of copying, all live objects can be compacted into the bottom of the new space, mitigating the fragmentation problem.But the immediate cost is the requirement of the doubled space compared to non-copying collectors.Unless the physical memory is large enough, this algorithm suffers more page faults than its non-copying counterparts.And after moving all data to the new space, the data cache memory will have been swept clean and will suffer cache misses when computation resumes.
A final method, and the one we will use as a starting point is "generational" garbage collection [Appel, 1989].A generational garbage collector not only reclaims memory efficiently but also compacts memory in a way that enhances locality.This algorithm divides memory into spaces.When one space is garbage collected, the live objects are moved to another space.It has been observed that some objects are long-lived and some are short-lived.By carefully arranging the objects, objects of similar ages can be kept in the same space, thus causing more frequent and small scalar GC's on certain spaces.This could preserve cache locality better than the plain copying algorithm.Its workload is proportional to the number of the live objects in a subspace instead of all in the entire memory space as is the case of "Mark and Sweep".
To support our proposed research, we will be given access to a proprietary tool developed at Sun Microsystems (the original Java developers).This tool provides a dynamic trace of object activity as a Java program runs.We will develop software that models memory allocation/GC algorithms and memory hierarchies.We will then combine the Sun tracing tool and our memory model with a performance analyzing tool that will process the traces to provide data on locality and system performance.The following figure is our proposed structural setting for our study.With the help of the tool and our model, we will be able to first study the impact of the conventional GC schemes on memory locality and on actual system performance when running Java programs.
We will gain some insight into objects referencing behavior and characteristics in relation to memory allocation and GC through this initial study.Using these data, we will next characterize the optimum performance of an ideal GC algorithm, e.g. a generational GC that arranges objects perfectly by their life spans, or via other criteria, thus enhancing memory locality.Such an ideal algorithm will be based on an "oracle" and will therefore be unimplementable, but it will give a limit on how much performance improvement can be achieved.This study will be similar to the way that “Belady's Min” algorithm [Belady, 1966] has been used for studying replacement algorithms in conventional memory hierarchies.
Through our study about the characteristics of optimal GC performance, we hope gain insight that will lead to new implementable algorithms with similar characteristics.Our goal is to define one such algorithm, compare it with the conventional and ideal GC schemes, and measure its performance in term of locality enhancement and system performance improvement.
As a starting point, we have some ideas that might improve the generational GC algorithm.We hypothesize that a majority of the objects that are allocated around the same time tend to have similar life spans.For instance, most objects in an array are likely to be allocated together upon initialization and deserted together when the array is no longer used.As another example, most local objects declared at the beginning of a block of statements, or a scope, are likely to die together when they fall out of the scope.If this hypothesis holds, then we could assume most of the objects in a procedure have a similar life span, and have generation spaces indexed by stack frames.We also propose another correlation: different types of objects tend to have different life spans.How accurate the predictions are and how much this information would actually facilitate an effective GC are the typical questions we plan to examine.If these hypotheses are valid, then we could divide up the generation spaces more accurately, thus facilitating a more efficient GC, improving the memory locality and system performance.
As memory allocation and GC are critical to memory management and the locality, we think this research would be of valuable significance in improving system performance for Java programs (and possibly other object oriented languages).Equipped with ideas and supporting tools, we are confident that our research goals of investigating the automatic dynamic memory management will be fruitful and achievable within the next year.
[Collins, 1960] Geoge E. Collins.“A Method for Overlapping and Erasure of Lists,”
Communications of the ACM, vol.312, pp. 655-657, December 1960.
[McCarthy, 1960] John McCarthy.“Recursive Functions of Symbolic Expressions and Their Computation by
Machine,” Communications of the ACM, vol.3, pp.184-195, 1960.
[Minsky, 1963] Marvin L. Minsky.“A Lisp Garbage Collector Algorithm Using Serial Secondary Storage,”
Technical Report Memo 58(rev.), Project MAC,MIT,Cambridge,MA, December 1963.
[Appel, 1989] Andrew W. Appel.“Simple Generational Garbage Collection and Fast Allocation,”
Software Pratice and Experience, vol.19, no.2, pp.171-183, 1989.
[Belady, 1966] L. A. Belady, “A Study of Replacement Algorithms for a Virtual Storage Computer,”
IBM Systems Journal, vol.5, no.2, pp.78-101, 1966.
I took up a Java test with Merittrac (Chennai). I would like to put down the questions which might be helpful for others.
Others if have attended online test with Merittrac please add the questions you have faced in the comments below.
Section I : Apptitude - 20 Mins Section I I: Java 15 Questions - 20 Mins Section IIII : Java Programming - 2 of 3 gives questions - 20 Mins
Section I I:
1. How would garbage collection keep track on live objects and objects without reference
2. How would you enhance garbage collection ? (memory allocation or method of gc like single or gen...)
3. Name the super class of ArrayList and implemented interfaces
4. What is the output of the following code public class Test { public static void main(String a[]){ List li = new ArrayList(); li.add(46); li.add(2); li.add(new Integer(50)); li.add("List"); li.add(false); li.add(1.025); System.out.println(li); } }
5. Which of the following are unchecked exceptions (EOFException, NumberFormatException, FileNotFoundException, AssertionError)
6. Name the superclass of AssertionError ? (Thorwable, Error....)
7. Choose one of the option - A constructor cannot (Override, Overload, .....)
8. What will happen from the below code public class Test { public static void main(String a[]){ int x = 0; int y = 50/x; } }
9. What will happen in the following code public class Test { static{ print(10); } public static void print(int x){ try { System.out.println(x); } catch (Exception e) { } finally { System.out.println("The End"); } } }
10. Name the super class of Java (What a weird question)
11. Is it possible to throw exception from an overridden method
12. What is the output of the below code
public class Test { public static void main(String a[]){ try { if(a.length==0) return; System.out.println("Try Block..."); } catch (Exception e) { System.out.println("Exception Block..."); } finally { System.out.println("Final Block..."); } } }
Section III
Have to choose 2 out of 3 and write the program, compile, run and submit the code.
This is quite hard to finish in 20 mins. I completed only one question and the time was out !!!
Rather i would say the editor was too bad and slow. Even mouse provided dint work properly and was ridiculous. It would have been easy to write the code in a notepad rather than typing it in their wonderful test environment.
I choose "Inheritance" and was asked to write a program and compile which meets the below points
Write Employee class with id, name, salary, address with getter and setter
Override the toString() method and return employee details
Override the equals() method and check if same employee
Write a Manager class which extends the Employee class
This should have setSalary() method and increase the salary by 5% when called.