Sunday, December 27, 2015

Documenting Rest api using Swagger

Rest apis documentation has great significance when it comes to publishing and testing them. Swagger is a specification for documenting the Rest APIs. It comes with UI that can be used as a GUI to view and test the api.

Annotations provided :

 @Api
@ApiClass
@ApiError
@ApiErrors
@ApiOperation
@ApiParam
@ApiParamImplicit
@ApiParamsImplicit
@ApiProperty
@ApiResponse
@ApiResponses
@ApiModel

/api/api-docs. It is used by Swagger UI which itself is embedded into finalJAR archive and served by Jetty as static web resource.

sample demo :http://petstore.swagger.io/

Spring core : Annotations when to use what

 @Configuration: 
Annotation based configuration alternative to xml based configuration .This will be mostly used with @Bean to define bean at run time 
 for annotation-based configuration, as opposed to xml-based configuration. 

 @Bean:
 define bean at run time, should be under class annotated with @configuration 
 It is used to explicitly declare a single bean, rather letting spring to do it while classpath scanning.
 It decouple declaration from the class definition
 When we don't own the class, it might make sense to use @bean wherever its being used

 @Component:
Define bean at run time, should be under class annotated with @configuration 
 Requires @ComponentScan to allow autoscanning
By default, the bean instances of this class have the same name as the class name with a lowercase initial. On top of that, we can specify a different name using the optional value argument of this annotation.

@ConditionalOnMissingBean:
 conditional that only matches when the specified bean / with name is not already in the bean container.Typically available in spring boot applciation

@ConditionalOnClass:
Will create bean if com.thetechiehouse.MyServiceClass class exist in the class path.To be used in Spring boot env.
@Bean
@ConditionalOnClass(name ="com.thetechiehouse.MyServiceClass")

@ConditionalOnProperty:
@ConditionalOnProperty("app.somekey") // Bean registration hapen only when app.somekey is present
@ConditionalOnProperty(name='com.myproperty',  havingValue = "true")
@ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "sms") 
    //notification.service=sms
@Bean
Create bean only if a specific  property value is true.To be used in Spring boot env.
@ConditionalOnExpression("${xxx.YYY.enabled:true}")
similar to @ConditionalOnProperty but it's a bit slower

Uses 
//@Resources

@Resource (name="myBean")

//@Bean
@Bean(name = "myBean")
    public SomeClass someMethod() {
        return new SomeClass();

    }



//@ Autowired

@Autowired
or
@Autowired

@Qualifier("myBean")

What are differences among @Autowired vs @Inject vs @Resource


Annotataion              package
@Resourcejavax.annotation
@Injectjavax.inject
@Qualifierjavax.inject
@Autowiredorg.springframework.bean.factory


@Resource:
annotation based on JSR-250. @Resource is quite similar to @Autowired 
 @Autowired (Spring specific)

 @Autowired:
It is fundamentally about type-driven injection ie  that  a resource by-type,
with optional semantic qualifiers.
The bean name is considered a default qualifier value.
 It does  have the required field so this can be used if the field is null and required so.

@Inject:
Annotation based on JSR-330
replacement for Spring’s @Autowired annotation
It  does not have the required field so if it does not find a suitable object it will fail.
It has @Named similar to qualifier in case of autowired.

@Resource will narrow down the search first by name then by type and finally by Qualifiers (ignored if match is found by name). @Autowired and @Inject will narrow down the search first by type then by qualifier and finally by the name.

Since @Repository, @Service, @Configuration, and @Controller are all meta-annotations of @Component, they share the same bean naming behaviour

Saturday, December 26, 2015

GC configuration

In this blog, we'll understand the  GC configuration.

-Xmx2560m
-Xms2560m
-XX:CMSInitiatingOccupancyFraction
-Xloggc
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintGCDetails
-XX:+PrintGCTimeStamps
-XX:+PrintGCDateStamps  
GC settings  and significance

-Xmx2560m  // Max heap memory
-Xms2560m // min heap memory

Setting -Xms and -Xmx to the same value increases predictability by removing the most important sizing decision from the virtual machine. On the other hand, the virtual machine can't compensate if you make a poor choice.

-XX:NewSize=786m   //size of new generation

-XX:MaxNewSize=786m //Max size of new generation
-XX:NewRatio=2 Ratio of old/new generation sizes  // either of two NewSize/NewRatio needed.

-XX:PermSize 

-XX:MaxPermSize=512m // is the range of the size of the permanent generation, which is the non-heap memory

-XX:CMSInitiatingOccupancyFraction=70  // CMS will run after old generation reaches  that pecentage CMS (2560-786)*.7
 -XX:+UseCMSInitiatingOccupancyOnly // optional
CMSInitiatingOccupancyFraction is only used for the 1st collection unless -XX:+UseCMSInitiatingOccupancyOnly is set. 
 default value is approximately 68%. 

-XX
:SurvivorRatio=8 // surviver space will be 1/8th of eden space

-XX:+UseCMSInitiatingOccupancyOnly // if not set the little contiguous free space (i.e. fragmentation) in oldgen a variable which could trigger CMS prior to the set occupancy fraction? 
I.e. is CMS smart enough to take into account the possibility of of clearing out dead objects (thus, reducing fragmentation) before hitting a promotion failure

XX:+CMSScavengeBeforeRemark // This flag allows the JVM to perform a minor GC on the young generation before re-marking, so that the number of objects remaining to be marked in the young gen will be much lower than before the GC. By default, this flag is disabled.

If you don't set the latter switch then, after the first one, the usual heuristics
 (which are based on allocation stats gathered during runtime) are used to determine when CMS starts. 

-Xloggc:<gc_file_location>/logs/gc.log // specify gc log file location
-XX:+PrintTenuringDistribution

XX:+PrintGCApplicationStoppedTime:Total time for which application threads were stopped 
 -XX:+PrintGCApplicationConcurrentTime:Application time
sample output:
Application time: 0.2863875 seconds
Total time for which application threads were stopped: 0.0225087 seconds
Application time: 0.1476791 seconds

Total time for which application threads were stopped: 0.0255697 seconds
-XX:+PrintGCDetails // activate detailed gc logging 
eg.
[GC
    [PSYoungGen: 142816K->10752K(142848K)] 246648K->243136K(375296K),
    0,0935090 secs
]
[Times: user=0,55 sys=0,10, real=0,09 secs]

[Full GC
    [PSYoungGen: 10752K->9707K(142848K)]
    [ParOldGen: 232384K->232244K(485888K)] 243136K->241951K(628736K)
    [PSPermGen: 3162K->3161K(21504K)],
    1,5265450 secs
]
[Times: user=10,96 sys=0,06, real=1,53 secs]

XX:+PrintGCTimeStamps and -XX:+PrintGCDateStamps// each line starts with absolute date and time when the logging was written

-XX:+UseConcMarkSweepGC //enable concurrentMarkSweep used for old generation collections
with this most of the gc works happens in the background without stopping application threads.In this applications threads getting stopped kept minimum.

======================================================
-XX:ConcGCThreads=<> //2,3...Number of threads with which the concurrent phase CMS will run.
It is related to ParallelGCThreads

-XX:ParallelGCThreads

The number of garbage collector threads in the young and old generations 
-XX:+UseParallelG // enable throughput collectors

Frequent GC keeps happening at very short interval . This can happen  each times when it is serving request . This is required to cleanup  the short-lived (=new) object  from each request. as they required to to get cleaned up.
 The pause rate is actually very low 0.2/sec and the max pause time of <20ms is good.

Be sure to increase the memory as you increase the number of processors, since allocation can be parallelized.

First we should have the settings using the default settings provided by jvm, then the tuning can be started so that the improvement can be noticed on production. GC viewer:https://github.com/chewiebug/GCViewer