Tuesday, March 20, 2018

Spring / Spring boot Authentication implementation with testing and walkthrough



Spring / Spring boot Authentication implementation with testing and walkthrough

https://www.future-processing.pl/blog/exploring-spring-boot-and-spring-security-custom-token-based-authentication-of-rest-services-with-spring-security-and-pinch-of-spring-java-configuration-and-spring-integration-testing/

Friday, September 19, 2014

Iterating over collections in Java 8 | JavaWorld

Iterating over collections in Java 8 | JavaWorld:



The Java platform includes a variety of ways to iterate over a collection of objects, including new options based on features introduced in Java 8. In this article John Moore revisits the Iterator design pattern with attention to the difference between active and passive iterators. Learn how Java 8's forEach() method and features of the Stream API can help you fine-tune and parallelize the behavior of Java iterators, then conclude with some performance benchmarks that might surprise you.



'via Blog this'

Thursday, September 18, 2014

String.intern in Java 6, 7 and 8 - string pooling  - Java Performance Tuning Guide

String.intern in Java 6, 7 and 8 - string pooling  - Java Performance Tuning Guide:



This article will describe how String.intern method was implemented in Java 6 and what changes were made in it in Java 7 and Java 8.
First of all I want to thank Yannis Bres for inspiring me to write this article.
07 June 2014 update: added 60013 as a default string pool size since Java 7u40 (instead of Java 8), added -XX:+PrintFlagsFinal and -XX:+PrintStringTableStatistics JVM parameter references, cleaned up a few typos.
This is an updated version of this article including -XX:StringTableSize=N JVM parameter description. This article is followed by String.intern in Java 6, 7 and 8 – multithreaded access article describing the performance characteristics of the multithreaded access to String.intern().

String pooling

String pooling (aka string canonicalisation) is a process of replacing severalString objects with equal value but different identity with a single shared Stringobject. You can achieve this goal by keeping your own Map<String, String> (with possibly soft or weak references depending on your requirements) and using map values as canonicalised values. Or you can use String.intern() method which is provided to you by JDK.
At times of Java 6 using String.intern() was forbidden by many standards due to a high possibility to get an OutOfMemoryException if pooling went out of control. Oracle Java 7 implementation of string pooling was changed considerably. You can look for details in http://bugs.sun.com/view_bug.do?bug_id=6962931 and http://bugs.sun.com/view_bug.do?bug_id=6962930.

String.intern() in Java 6

In those good old days all interned strings were stored in the PermGen – thefixed size part of heap mainly used for storing loaded classes and string pool. Besides explicitly interned strings, PermGen string pool also contained all literal strings earlier used in your program (the important word here is used – if a class or method was never loaded/called, any constants defined in it will not be loaded).
The biggest issue with such string pool in Java 6 was its location – the PermGen. PermGen has a fixed size and can not be expanded at runtime. You can set it using -XX:MaxPermSize=N option. As far as I know, the default PermGen size varies between 32M and 96M depending on the platform. You can increase its size, but its size will still be fixed. Such limitation required very careful usage ofString.intern – you’d better not intern any uncontrolled user input using this method. That’s why string pooling at times of Java 6 was mostly implemented in the manually managed maps.

String.intern() in Java 7

Oracle engineers made an extremely important change to the string pooling logic in Java 7 – the string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application. Technically, this alone could be a sufficient reason to reconsider using String.intern() in your Java 7 programs. But there are other reasons.
For more refer the article.


'via Blog this'

Wednesday, September 18, 2013

Spring Framework


Spring framework is a suite of frameworks which widely touches most of the problem areas that java visits today.

Spring Core foundation provides a way to soft-declare and wire applicaiton objects which live through the life of the application. It also defines the inter-dependencies amongst these application objects.

By doing so Spring makes it easy to swap in-and-out application specific objects/functionalities very easily.

Its kind of like plug-n-program software paradigm providing APIS via its collection frameworks  which solve different Java problems.

By doing this Spring allows the developer to focus more on the application domain then the complex programming aspects.

Spring essentially is abstracting/encapsulating the programming complexity behind it providing the developer
and easy way to readily jump on the business logic since the structure of the application has been moved to a
more declarative form so while writing code developer focuses more on the business logic then structuring mechanical apects of the application.



Wednesday, July 18, 2012

ThreadLocal

http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable


Classloader leaks: the dreaded "java.lang.OutOfMemoryError: PermGen space" exception

Did you ever encounter a java.lang.OutOfMemoryError: PermGen space error when you redeployed your application to an application server? Did you curse the application server, while restarting the application server, to continue with your work thinking that this is clearly a bug in the application server. Those application server developers should get their act together, shouldn't they? Well, perhaps. But perhaps it's really  your fault!
Take a look at the following example of an innocent looking servlet.
package com.stc.test;

import java.io.\*;
import java.util.logging.\*;
import javax.servlet.\*;
import javax.servlet.http.\*;

public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Log at a custom level
Level customLevel = new Level("OOPS", 555) {};
Logger.getLogger("test").log(customLevel, "doGet() called");
}
}
Try to redeploy this little sample a number of times.  I bet this will eventually fail with the dreadedjava.lang.OutOfMemoryError: PermGen space error. If you like to understand what's happening, read on.

The problem in a nutshell

Application servers such as Glassfish allow you to write an application (.ear, .war, etc) and deploy this application with other applications on this application server. Should you feel the need to make a change to your application, you can simply make the change in your source code, compile the source, and redeploy the application without affecting the other still running applications in the application server: you don't need to restart the application server. This mechanism works fine on Glassfish and other application servers (e.g. Java CAPS Integration Server).
The way that this works is that each application is loaded using its own classloader. Simply put, a classloader is a special class that loads .class files from jar files. When you undeploy the application, the classloader is discarded and it and all the classes that it loaded, should be garbage collected sooner or later.
Somehow, something may hold on to the classloader however, and prevent it from being garbage collected. And that's what's causing the java.lang.OutOfMemoryError: PermGen space exception.

PermGen space 

What is PermGen space anyways? The memory in the Virtual Machine is divided into a number of regions. One of these regions is PermGen. It's an area of memory that is used to (among other things) load class files. The size of this memory region is fixed, i.e. it does not change when the VM is running. You can specify the size of this region with a commandline switch: -XX:MaxPermSize . The default is 64 Mb on the Sun VMs.
If there's a problem with garbage collecting classes and if you keep loading new classes, the VM will run out of space in that memory region, even if there's plenty of memory available on the heap. Setting the -Xmx parameter will not help: this parameter only specifies the size of the total heap and does not affect the size of the PermGen region.

Garbage collecting and classloaders

When you write something silly like
 private void x1() {
        for (;;) {
            List c = new ArrayList();
        }
    }
you're continuously allocating objects; yet the program doesn't run out of memory: the objects that you create are garbage collected thereby freeing up space so that you can allocate another object. An object can only be garbage collected if the object is "unreachable". What this means is that there is no way to access the object from anywhere in the program. If nobody can access the object, there's no point in keeping the object, so it gets garbage collected. Let's take a look at the memory picture of the servlet example. First, let's even further simplify this example:
package com.stc.test;

import java.io.\*;
import java.net.\*;
import javax.servlet.\*;
import javax.servlet.http.\*;

public class Servlet1 extends HttpServlet {
private static final String STATICNAME = "Simple";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
After loading the above servlet, the following objects are in memory (ofcourse limited to the relevant ones):

In this picture you see the objects loaded by the application classloader in yellow, and the rest in green. You see a simplified container object that holds references to the application classloader that was created just for this application, and to the servlet instance so that the container can invoke the doGet() method on it when a web request comes in. Note that the STATICNAME object is owned by the class object. Other important things to notice:
  1. Like each object, the Servlet1 instance holds a reference to its class (Servlet1.class).
  2. Each class object (e.g. Servlet1.class) holds a reference to the classloader that loaded it.
  3. Each classloader holds references to all the classes that it loaded.
The important consequence of this is that whenever an object outside of AppClassloader holds a reference to an object loaded by AppClassloadernone of the classes can be garbage collected.

To illustrate this, let's see what happens when the application gets undeployed: the Container object nullifies its references to the Servlet1 instance and to the AppClassloader object.

As you can see, none of the objects are reachable, so they all can be garbage collected. Now let's see what happens when we use the original example where we use the Level class:
package com.stc.test;

import java.io.\*;
import java.net.\*;
import java.util.logging.\*;
import javax.servlet.\*;
import javax.servlet.http.\*;

public class LeakServlet extends HttpServlet {
private static final String STATICNAME = "This leaks!";
private static final Level CUSTOMLEVEL = new Level("test", 550) {}; // anon class!

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Logger.getLogger("test").log(CUSTOMLEVEL, "doGet called");
}
}
Note that the CUSTOMLEVEL's class is an anonymous class. That is necessary because the constructor of Level is protected. Let's take a look at the memory picture of this scenario:

In this picture you see something you may not have expected: the Level class holds a static member to all Level objects that were created. Here's the constructor of the Level class in the JDK:
 protected Level(String name, int value) {
this.name = name;
this.value = value;
synchronized (Level.class) {
known.add(this);
}
}
Here known is a static ArrayList in the Level class. Now what happens if the application is undeployed?

Only the LeakServlet object can be garbage collected. Because of the reference to the CUSTOMLEVEL object from outside ofAppClassloader, the  CUSTOMLEVEL anyonymous class objects (LeakServlet$1.class) cannot be garbage collected, and through that neither can the AppClassloader, and hence none of the classes that the AppClassloader loaded can be garbage collected.
Conclusion: any reference from outside the application to an object in the application of which the class is loaded by the application's classloader will cause a classloader leak.

More sneaky problems 

I don't blame you if you didn't see the problem with the Level class: it's sneaky. Last year we had some undeployment problems in our application server. My team, in particular Edward Chou, spent some time to track them all down. Next to the problem with Level, here are some other problems Edward and I encountered. For instance, if you happen to use some of the Apache Commons BeanHelper's code: there's a static cache in that code that refers to Method objects. The Methodobject holds a reference to the class the Method points to. Not a problem if the Apache Commons code is loaded in your application's classloader. However, you do have a problem if this code is also present in the classpath of the application server because those classes take precedence. As a result now you have references to classes in your application from the application server's classloader... a classloader leak!
I did not mentiond yet the simplest recipe for disaster: a thread started by the application while the thread does not exit after the application is undeployed.

Detection and solution

Classloader leaks are difficult. Detecting if there's such a leak without having to deploy/undeploy a large number of times is difficult. Finding the source of a classloader leak is even trickier. This is because all the profilers that we tried at the time, did not follow links through classloaders. Therefore we resorted to writing some custom code to find the leaks from memory dump files. Since that exercise, new tools came to market in JDK 6. The next blog will outline what the easiest approach today is for tracking down a glassloader leak.


ThreadLocal and memory leaks

(imported from http://blogs.codehaus.org/people/avasseur, read comments there)

Last day I realized that using ThreadLocal can be very dangerous when it comes to long running applications and garbage collections.

When you read the documentation of the ThreadLocal, you read that the object put in a ThreadLocal context is associated to the thread, and will be garbaged once the thread is dead.


Each thread holds an implicit reference to its copy of a ThreadLocal as long as the thread is alive and the ThreadLocal object is accessible; after a thread goes away, all of its copies of ThreadLocal variables are subject to garbage collection (unless other references to these copies exist).


So if you use ThreadLocal to store some object instance there is a high risk to have the object stored in the thread local never garbaged when your app runs inside an app server like WebLogic Server, which manage a pool of working thread - even when the class that created this ThreadLocal instance is garbage collected.

To solve this issue, you will probably have to check for it first with a memory profiler tool like JProfiler, and then wrap the value put in the ThreadLocal in a WeakReference.

That did not appears to be obvious while reading the javadoc. Isn't it ?

Saturday, March 10, 2012

Database Systems



Transaction Isolation Levels:- Defines the scope of data visibility between 2 or more concurrent transactions.



READ UNCOMITTED 


Transactions can read uncommitted (garbage/dirty) data. 
Provides higher throughput. No Locking/Synchronization.
Dirty read is possbile.
Not supported in Oracle


READ COMITTED


Transactions can read only commited data but that data can change during the transaction life cycle.
Provides higher throughput/ No locking Synchronization.
On every read you may get different data.
Oracle Database meets the READ COMMITTED isolation standard. 
This is the default mode for all Oracle Database applications.


REPEATABLE READ


Transactions will get the same data (in rows) for every read. But there may be new rows.
No protection against INSERTS from other transactions.
At any point in a trasaction the read rows are locked so on future reads there may be new rows.
High chances of DEADLOCK. Performance hit (Low throughput)
Oracle Database does not normally support this isolation level, except as provided by SERIALIZABLE.


SERIALIZABLE


Transactions lock/synchronize on the table. 
At any point in the given transaction always same data is read. There are no new rows.
Protects against INSERTS from other transactions.
Very High chances of DEADLOCK. Very low throughput.
Oracle Database does not normally support this isolation level, except as provided by SERIALIZABLE.


Practically, transaction isolation level => READ COMMITTED on the database + use SELECT FOR - UPDATE OR TABLE LOCKING (for data synchronization)


http://docs.oracle.com/cd/B13789_01/appdev.101/b10795/adfns_sq.htm#1024753




SELECT FOR - UPDATE


Use it for locking selective rows that you are working on.
The lock is released on commit or rollback.


-------------------------------------------------------------------------------------------------------------------------------------------------------


CURSORS - is a view of data (window of data)


IMPLICIT -  DML's are implicit cursor (Select/update). DB behind the scenes will start a cursor for every SELECT or UPDATE


EXPLICIT - They can be used in the apps like ProC or in Stored Procs etc where you explicityly define a cursor and then provide a query for data selection.




STATIC  - opens a new cursor every time a new query comes in to the DB.


DYNAMIC - Reuses the same cursor for the similar (with parameters) or same queries.
Database System will create such cursors (process) in shared area. By doing this Databases optimize resource allocation by sharing resources.


Statement s = new Connection.createStatement()

Will always create a new static cursor
Database will never spend time looking for whether the cursor (for query) already exists.

Prepared Statement p = Connection.prepareStatement()

Will check with the database if the compiled query (cursor) already exists. If it does then
the database will returns the existing cursor context.
On first run it will always create a new statement since it wont exist.




Sunday, March 4, 2012

Concurency

Context Switches involved in notify notifyAll and conditional notify.

- Conditional Notify () works best.
- A signal from Notify () can be easily missed - see how
- NotifyAll() wakes up all threads and puts them into runnable state. Hence involves context switches (for each thread woken up)


Antipattern

http://en.wikipedia.org/wiki/Anti-pattern#Software_design_anti-patterns

Static Imports (since Java 5.0) 


Static import is a feature introduced in the Java programming language that allows members (fields and methods) defined in a class as public static to be used in Java code without specifying the class in which the field is defined. This feature was introduced into the language in version 5.0.
The feature provides a typesafe mechanism to include constants into code without having to reference the class that originally defined the field. It also helps to deprecate the practice of creating a constant interface: an interface that only defines constants then writing a class implementing that interface, which is considered an inappropriate use of interfaces[1].

import static java.lang.Math.*;

import static java.lang.Math.PI;
For custom constants Create a Constant class 


BINARY semaphore:

DO WAIT : SSC

Synchronize - Spin (while:signal notset to true -> this.wait()) - Clear (set signal to false)

DONOTIFY: SSN
Synchronize - Signal( set signal to true) - Notify


public class QueueObject {

  private boolean isNotified = false;

  public synchronized void doWait() throws InterruptedException {
    while(!isNotified){
        this.wait();
    }
    this.isNotified = false;
  }

  public synchronized void doNotify() {
    this.isNotified = true;
    this.notify();
  }

  public boolean equals(Object o) {
    return this == o;
  }
}