Sunday, 1 April 2018

Avoiding Flickering in jQuery

Why Flickering occurs :

A flash of unstyled content is an instance where a web page appears briefly with the browser's default styles prior to loading an external CSS stylesheet, due to the web browser engine rendering the page before all information is retrieved. The page corrects itself as soon as the style rules are loaded and applied; however, the shift may be distracting.  

Solution to handle - properly styled :

 <div id="some-div" style="display:none">... content ... </div>. 

Then use jQuery to show it when the entire document is ready:

$(function() {
 $("#some-div").show();
 });

To prevent caching in Internet Explorer

The following 3 ways to prevent caching in the Internet Explorer.

  • HTTP-EQUIV META Tags 
  • In Controller 
  • AJAX 
HTTP-EQUIV META Tags : 
HTML pages allow for a special HTTP-EQUIV form of the META tag that specifies particular HTTP headers from within the HTML document. Here is a short example HTML page that uses both Pragma: no-cache and Expires: -1:
<HTML><HEAD>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
</HEAD><BODY>
</BODY>
</HTML>
  • Pragma: no-cache prevents caching only when used over a secure connection. A Pragma: no-cache META tag is treated identically to Expires: -1 if used in a non-secure page. The page will be cached but marked as immediately expired.
  • Cache-Control META HTTP-EQUIV tags are ignored and have no effect in Internet Explorer versions 4 or 5. To use Cache-Control this header must be specified using HTTP headers as described in the Cache-Control section above.
  • Note that the use of standard HTTP headers are much preferred over META tags. META tags typically must appear at the top of the HTML HEAD section. And there is at least one known problem with the Pragma HTTP-EQUIV META tag.
​​
In Controller in ASP.NET MVC: 

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public abstract class BaseController : Controller
{

AJAX :
$.ajax({
    url: '/controller/action',
    type: 'GET',
    cache: false,
    success: function(result) {

    }
});

The long-awaited release of Java 9 brought a lot of changes and interesting new features.

The State of Java in 2018


2017 has been a turbulent year in the Java world. The long-awaited release of Java 9 brought a lot of changes and interesting new features, and Oracle announced a new release schedule for the JDK.
And that was just the beginning. In the past, developers often complained that Java wasn’t developing fast enough. I don’t think you will hear these complaints in the near future. It might be quite the opposite.

Inline image 1

What’s in store for 2018

In 2018, the JDK will follow a new release schedule. Instead of a huge release every few years, you will get a smaller one every six months. So, after the release of Java 9 in September 2017, Java 10 is already planned for March 2018. But more about that later.

Enterprise Stack Overview

Most enterprise projects don’t use the JDK alone. They also rely on a stack of enterprise libraries, like Spring Boot or Java EE, which will also evolve over the next several months. In this article, I will mostly focus on the JDK. But here is a quick overview of what you should expect from the two major enterprise stacks in the Java world.
The Spring development team is working hard on Spring Boot 2 and released the first release candidate in January. The team doesn’t expect any major API changes and doesn’t plan to add any new features until the final release. So, if you are using Spring Boot in your projects, it’s about time to take a closer look at the new version and to plan the updates of your existing Spring Boot applications.
At the end of 2017, Oracle started to hand over the Java EE specifications to the EE4J project managed by the Eclipse Foundation. As expected, such a transfer is a huge project which can’t be completed in a few days. There is a lot of organizational and technical work that still needs to be done. Java EE needs a new name and development process. And the transfer of the source code and all the artifacts stored in different bug trackers is still ongoing. We will have to wait a little bit longer before we can see the effects of the transfer and the stronger community participation.

Short JDK release and support cycles

As announced last year, Oracle will release two new JDK versions in 2018. Instead of the slow release cycle where every few years produced a new major release with lots of changes, we will now get a smaller feature release every six months. This allows for faster innovation of the Java platform. It also reduces the associated risks of a Java update. For Java developers, these smaller releases will also make it a lot easier to get familiar with the latest changes and to apply them to our projects.
I expect this to be a very positive change for the Java world. It will add a new dynamic to the development of the Java language, and allows the JDK team to adapt and innovate a lot faster.

Changes and new features in JDK 10

Due to the short release cycle, Java 10 only brings a small set of changes. You can get an overview of the currently included 12 JEPs (JDK Enhancement Proposal) on the OpenJDK’s JDK10 page.
The most notable change is probably the support for type inference of local variables (JEP 286). But you should also know about the new time-based release versioning (JEP 322), and parallel full GC (garbage collector) support added to G1, or Garbage First (JEP 307).

Type inference

JDK 10 will finally introduce type inference to the Java language. Most other statically-typed languages have been supporting this feature for quite a while, and a lot of Java developers have been asking for it.
JEP 286 introduces the keyword var, which shortens the declaration of a local variable. It tells the compiler to infer the type of the variable from its initializer. So, instead of:
List<String> paramNames = List.of("host.name", "host.port");
Configuration config = initializeConfig(paramNames);
you will be able to write:
var paramNames = List.of("host.name", "host.port");
var config = initializeConfig(paramNames);
As you can see in the code snippets, the keyword var removes the redundancy from the variable declaration. This can make your code easier to read, especially if you use good variable names and if it’s a variable that you only use a few times directly after you declared it.
If you want to dive deeper into JEP 286 and when you should use it, I recommend you take a look at Nicolai Parlog’s very detailed article about type inference in Java 10.

Time-based release versioning

Beginning with Java 10, the format of the Java version number changes to improve the support for a time-based release model.
The main challenge introduced by the new release model is that the content of a release is subject to change. The only thing that’s defined in the beginning is the point in time at which the new version will be released. If the development of a new feature takes longer than expected, it doesn’t make the cut for the next release and will not be included. So, you need a version number that represents the passage of time, instead of the nature of the included changes.
JEP 322 defines the format of the version number as $FEATURE.$INTERIM.$UPDATE.$PATCH, and plans to use it as follows:
  • Every six months, the development team will publish a new feature release, and increment the $FEATURE part of the version number.
  • The release published in March 2018 will be called JDK 10, and the one in September JDK 11. The development team states in JEP 223 that they expect to ship at least one to two significant features in each feature release.
  • The $INTERIM number is kept for flexibility and will not be used in the currently planned 6-month release model. So, for now, it will always be 0.
  • Updates will be released between the feature releases and shall not include any incompatible changes. One month after a feature release and after that every three months, the $UPDATE part of the version number will be incremented.

Parallel full GC in G1

For most developers, this is one of the smaller changes. Depending on your application, you might not even recognize it.
G1 became the default garbage collector in JDK 9. Its design tries to avoid full garbage collections, but that doesn’t mean that they never happen. Unfortunately, G1 only uses a single-threaded mark-sweep-compact algorithm to perform a full collection. This might result in a performance decrease compared to the previously used parallel collector.
JEP 307 addresses this issue by providing a multi-threaded implementation of the algorithm. Beginning with JDK 10, it will use the same number of threads for full collections as it applies for young and mixed collections.
So, if your application forces the garbage collector to perform full collections, JDK 10 might improve its performance.

Plans for JDK 11

JDK 10 isn’t even released yet, and there are only seven months left until the release of JDK 11. So, it’s no surprise that there is already a small set of JEPs planned for the second feature release in 2018.
In addition to the removal of deprecated Java EE and CORBA modules (JEP 320) and a new garbage collector (JEP 318), JDK 11 will most likely introduce dynamic class-file constants (JEP 309), and support the keyword var for implicitly-typed lambda expressions (JEP 323).
The current scope of JDK 11 shows the benefits of shorter release cycles. The JEPs 309 and 318 introduce new functionality, while the other two JEPs use an iterative approach to evolve existing features.
With the release of JDK 9 in September 2017, the Java EE and CORBA modules became deprecated. One year later, with the release of JDK 11, JEP 320 removes them from the JDK. So, instead of keeping them for several years, they will be removed in a timely and predictable way.
And JEP 323 is a logical next step after JEP 286 introduced type inference for local variables in JDK 10. You should expect to see this approach more often in the future. The short release cycles make it a lot easier to ship a huge feature in multiple, logical steps distributed over one or more feature releases.

Short support cycles require fast adoption

Together with the new release model, Oracle also changed their support model. The new model differentiates between short-term and long-term releases.
Short-term releases, like Java 9 and 10, will only receive public updates until the next feature release gets published. So support for Java 9 ends in March 2018, and Java 10 will not receive any public updates after September 2018.
Java 11 will be the first long-term release. Oracle wants to support these releases for a more extended period. But until now, they didn’t announce how long they will provide public updates for Java 11.
As an application developer, you will need to decide if you want to update your Java version every six months, or if you prefer a long-term release every few years. In addition to that, Oracle encourages everyone to migrate to their Java SE Advanced product. It includes at least five years of support for every long-term release.

Summary

In the past, a lot of developers complained about the slow evolution of the Java language. That will no longer be the case in 2018. The new, 6-month release cycle and the adapted support model will enforce faster updates of existing applications and introduce new features on a regular basis. In combination with the evolution of existing frameworks, like Java EE or Spring, this will add a new dynamic to the Java world. And it will also require a mindset shift in all companies that are used to updating their applications every few years.
Source From : https://stackify.com/java-2018/?utm_source=onesignal&utm_medium=PushNotificaiton&utm_campaign=State_of_Java

Understanding OutOfMemoryError Exception in Java


In Java, all objects are stored in the heap. They are allocated using new operator. The OutOfMemoryError Exception in Java looks like this:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
Usually, this error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
OutOfMemoryError usually means that you’re doing something wrong, either holding onto objects too long, or trying to process too much data at a time. Sometimes, it indicates a problem that’s out of your control, such as a third-party library that caches strings, or an application server that doesn’t clean up after deploys. And sometimes, it has nothing to do with objects on the heap.
The java.lang.OutOfMemoryError exception can also be thrown by native library code when a native allocation cannot be satisfied (for example, if swap space is low). Let us understand various cases when the OutOfMemory error might occur.
Symptom or Root cause?
To find the cause, the text of the exception includes a detailed message at the end. Lets examine all the errors.
  1. Error 1 – Java heap space : This error arises due to the applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time. Instead, after garbage collection, the objects are queued for finalization, which occurs at a later time. Implementation:
    • finalizers are executed by a daemon thread that services the finalization queue.
    • If the finalizer thread cannot keep up, with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.
    • The problem can also be as simple as a configuration issue, where the specified heap size (or the default size, if it is not specified) is insufficient for the application.
    // Java program to illustrate
    // Heap error
    import java.util.*;
     
    public class Heap {
        static List<String> list = new ArrayList<String>();
     
    public static void main(String args[]) throws Exception
        {
            Integer[] array = new Integer[10000 * 10000];
        }
    }

    When you execute the above code above you might expect it to run forever without any problems. As a result, over time, with the leaking code constantly used, the “cached” results end up consuming a lot of Java heap space and when the leaked memory fills all of the available memory in the heap region and Garbage Collection is not able to clean it, the java.lang.OutOfMemoryError:Java heap space is thrown.
    Prevention : Check how to monitor objects for which finalization is pending in Monitor the Objects Pending Finalization.
  2. Error 2 – GC Overhead limit exceeded : This error indicates that the garbage collector is running all the time and Java program is making very slow progress. After a garbage collection, if the Java process is spending more than approximately 98% of its time doing garbage collection and if it is recovering less than 2% of the heap and has been doing so far the last 5 (compile time constant) consecutive garbage collections, then a java.lang.OutOfMemoryError is thrown.
    This exception is typically thrown because the amount of live data barely fits into the Java heap having little free space for new allocations.
    // Java program to illustrate
    // GC Overhead limit exceeded
    import java.util.*;
     
    public class Wrapper {
    public static void main(String args[]) throws Exception
        {
            Map m = new HashMap();
            m = System.getProperties();
            Random r = new Random();
            while (true) {
                m.put(r.nextInt(), "randomValue");
            }
        }
    }

    If you’ll run this program with java -Xmx100m -XX:+UseParallelGC Wrapper then the output will be something like this :
    Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
        at java.lang.Integer.valueOf(Integer.java:832)
        at Wrapper.main(error.java:9)
    
    Prevention : Increase the heap size and turn off it with the command line flag -XX:-UseGCOverheadLimit.
  3. Error 3 – Permgen space is thrown : Java memory is separated into different regions. The size of all those regions, including the permgen area, is set during the JVM launch. If you do not set the sizes yourself, platform-specific defaults will be used.
    The java.lang.OutOfMemoryError: PermGen space error indicates that the Permanent Generation’s area in memory is exhausted.
    // Java program to illustrate
    // Permgen Space error
    import javassist.ClassPool;
     
    public class Permgen {
        static ClassPool classPool = ClassPool.getDefault();
     
    public static void main(String args[]) throws Exception
        {
            for (int i = 0; i < 1000000000; i++) {
                Class c = classPool.makeClass(com.saket.demo.Permgen" + i).toClass();
                System.out.println(c.getName());
            }
        }
    }
    In the above sample code, code iterates over a loop and generates classes at run time. Class generation complexity is being taken care of by the Javassist library.
    Running the above code will keep generating new classes and loading their definitions into Permgen space until the space is fully utilized and the java.lang.OutOfMemoryError: Permgen space is thrown.
    Prevention : When the OutOfMemoryError due to PermGen exhaustion is caused during the application launch, the solution is simple. The application just needs more room to load all the classes to the PermGen area so we just need to increase its size. To do so, alter your application launch configuration and add (or increase if present) the -XX:MaxPermSize parameter similar to the following example:
    java -XX:MaxPermSize=512m com.saket.demo.Permgen
    
  4. Error 4 – Metaspace : Java class metadata is allocated in native memory. If metaspace for class metadata is exhausted, a java.lang.OutOfMemoryError exception with a detail MetaSpace is thrown.
    The amount of metaspace that can be used for class metadata is limited by the parameter MaxMetaSpaceSize, which is specified on the command line. When the amount of native memory needed for a class metadata exceeds MaxMetaSpaceSize, a java.lang.OutOfMemoryError exception with a detail MetaSpace is thrown.
    // Java program to illustrate
    // Metaspace error
    import java.util.*;
     
    public class Metaspace {
        static javassist.ClassPool cp = javassist.ClassPool.getDefault();
     
    public static void main(String args[]) throws Exception
        {
            for (int i = 0; i < 100000; i++) {
                Class c = cp.makeClass("com.saket.demo.Metaspace" + i).toClass();
            }
        }
    }

    This code will keep generating new classes and loading their definitions to Metaspace until the space is fully utilized and the java.lang.OutOfMemoryError: Metaspace is thrown. When launched with -XX:MaxMetaspaceSize=64m then on Mac OS X my Java 1.8.0_05 dies at around 70, 000 classes loaded.
    Prevention : If MaxMetaSpaceSize, has been set on the command-line, increase its value. MetaSpace is allocated from the same address spaces as the Java heap. Reducing the size of the Java heap will make more space available for MetaSpace. This is only a correct trade-off if there is an excess of free space in the Java heap.
  5. Error 5 – Requested array size exceeds VM limit : This error indicates that the application attempted to allocate an array that is larger than the heap size. For example, if an application attempts to allocate an array of 1024 MB but the maximum heap size is 512 MB then OutOfMemoryError will be thrown with “Requested array size exceeds VM limit”.
    // Java program to illustrate
    // Requested array size
    // exceeds VM limit error
    import java.util.*;
     
    public class GFG {
        static List<String> list = new ArrayList<String>();
     
    public static void main(String args[]) throws