HASHMAP IN JAVA

A map is an interface in the java.util package which stores the association between key and its corresponding value. A map cannot contain duplicate keys; each key can map to at most one value Map differs from array in a way that we can store a value at a particular index in arrays but a Map determines the index itself and does this based on the value on the key.
HASHMAP is a class which implements the map interface.
Hash map is a data structure which uses a hash function to map identifying values, known as keys (e.g., a person’s name) to their associated values (e.g., their telephone number).
The hash function transforms the key into the index (the hash) of an array element where the corresponding value is to be sought.
Take for instance the case of a phonebook. you can have a map where the keys are phone numbers and the value is the name of the person..
Given a key you can find its value.
Ex.[“key”, “value”]=[“88028”,”vinay”]
With the given key value i.e 88028 one can find its value….. which is vinay.
Take another example…..

import java.util.Map; 
import java.util.HashMap; 
 
public class Map_example { 
Map<Integer, String> addPhoneNum = new HashMap<Integer, String>(); 
public void addPhoneNum(Integer phonenumber, String name) { 
addPhoneNum.put(phonenumber, name); 
} 
public String getName(Integer phonenumber) { 
return addPhoneNum.get(phonenumber); 
} 
 public static void main(String[] args) { 
Map_example m1 = new Map_example(); 
m1.addPhoneNum(9911538992 "vinay"); 
 
System.out.println( 
m1.getName(9911538992)); 
 
} 

Main features of HASHMAP are.
• HashMap is a library class in Java.
• It is already implemented, hence can be used immediately HashMap is a library class in Java.
• HashMap stores only object references. That’s why, it’s impossible to use primitive data types like double or int. Use wrapper class (like Integer or Double) instead.
• For multi-theaded(synchronized) array class use Hashtable (java.lang.Hashtable)

The two most important HashMap’s methods are:
• get( Object key ) –this method returns the value associated with specified key in this hash map, or null if there is no value for this key
• put(K key, V value) – this method associates the specified value with the specified key in the map.

Internally a HashMap maintains an array. To have the HashMap work efficiently, the array must be large enough so that the key/value pairs are well-distributed and the performance is not affected. Therefore, the HashMap maintains two (customizable) variables :
1. Capacity
2. LoadFactor.
The capacity is the length of the internal array whereas the LoadFactor controls when the capacity should be increased.

QUARTZ FRAMEWORK IN JAVA

Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application – from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may executed virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering. Quartz is free, licensed under the Apache 2.0 license.
Quartz.NET is a pure .NET library written in C# which currently targets Framework version 1.1 and above. Quartz.NET is feature-wise equal to Quartz Java 1.6 excluding Java specifics. Quartz.NET is already running in production systems and has received good feedback.
Features
Quartz comprises from small java library (.jar file) that contains the core Quartz functionality and scheduler interface is the main interface (API) to this functionality. It needs little configuration to be set in the system. Simple scheduling process like scheduling jobs, un scheduling jobs, starting/stopping/pausing the scheduler can be done through it.
Example. –
For running any job we need to make few component.
Scheduler Task– It is simply a java class which we want to schedule.
Trigger– are used to define when Quartz will run your declared scheduled jobs.
It is of two type.https://www.techartifact.com/blogs/wp-admin/post-new.php#post_name
• SimpleTrigger – allows to set start time, end time, repeat interval to run yout job.
• CronTrigger – allows Unix cron expression to specify the dates and times to run your job.

We need to create a task which we want to schedule.

package com.vinay.jobs;
public class PrintMyNameTask
{
public void printMe() {
System.out.println(“My name is vinay” + new date());
}
}

After creating the task ,we need to make job so that we can schedule.for that we need to implement the Quartz Job interface, and also the execute() method. Get the scheduler task from Job Details via “task name”, and specify which schedule task (method) to run.
execute(): Any software components you want to schedule then you must implement the Job interface and override it execute() method.
JobExecutionContext: The JobExecutionContext object that is passed to execute() method provides the job instance with information about its “run-time” environment – a handle to the Scheduler that executed it, a handle to the Trigger that triggered the execution, the job’s JobDetail object, and a few other items.

package com.vinay.jobs;
import java.util.Map;
import org.quartz.Job;
public class NamePrintJob implements Job
{
public void execute(JobExecutionContext context)
{
Map dataMap = context.getJobDetail().getJobDataMap();
PrintMyNameTask task = (PrintMyNameJob)dataMap.get("printMyNametask");
task. printMe();
}
}

Initialize a JobDetail object, link your scheduler job with setJobClass(NamePrintJob.class); method, define a task name and put it into Job data map, dataMap.put(“printMyNameTask”, task);. This “task name” is the only link between your Job and JobDetail.
Note : job.setName(“printMyNameTaskJob”) has no special method or function,it is just a descriptive name, you can put anything here.
We will be doing scheduling using cron trigger

package com.vinay.jobs;
import java.util.Map;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;

public class VinayQuartzExample
{
public static void main( String[] args ) throws Exception
{
PrintMyNameTask task = new PrintMyNameTask();

JobDetail job = new JobDetail();
job.setName("namePrintJob ");
job.setJobClass(NamePrintJob.class);

Map dataMap = job.getJobDataMap();
dataMap.put("printMyNameTask ", task);

CronTrigger trigger = new CronTrigger();
trigger.setName("vinayjobSchedule");
trigger.setCronExpression("0 15 12 ? * * ");
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}

This task will run every 12:15 am everyday.
Crond Expression- cron is a UNIX tool that has been around for a long time, so its scheduling capabilities are powerful and proven. The CronTrigger class is based on the scheduling capabilities of cron.
CronTrigger uses “cron expressions”, which are able to create firing schedules such as: “At 8:00am every Monday through Friday” or “At 1:30am every last Friday of the month”.
Example-
0 0 12 * * ? Fire at 12pm (noon) every day
0 15 10 * * ? Fire at 10:15am every day
0 15 10 * * ? 2005 Fire at 10:15am every day during the year 2005
0 15 10 ? * 6L Fire at 10:15am on the last Friday of every month
0 15 10 ? * 6L 2002-2005 Fire at 10:15am on every last friday of every month during the years 2002, 2003, 2004 and 2005

If you want to build cron expression for you. Just use http://www.cronmaker.com/

Reference – http://www.mkyong.com/java/quartz-scheduler-example/
http://www.quartz-scheduler.org/docs/tutorials/crontrigger.html

Hibernate Caching

I found some useful information on internet about hibernate caching.I thought of sharing with everyone.
High-volume database traffic is a frequent cause of performance problems in Web applications. Hibernate is a high-performance, object/relational persistence and query service. In many cases, second-level caching can be just what Hibernate needs to realize its full performance-handling potential.

What is caching – Anything you can do to minimize traffic between a database and an application server is probably a good thing. In theory, an application ought to be able to maintain a cache containing data already loaded from the database, and only hit the database when information has to be updated. When the database is hit, the changes may invalidate the cache.

There are two different cache used in hibernate-
1. First Level cache – This is associated with session. This is default implemented in hibernate on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications
2. Second level cache – This is associated with Session Factory object. It will survive Sessions and can be reused in new Session by same SessionFactory (which usually is one per application). By default the 2nd level cache is not enabled. This ‘second-level’ cache exists as long as the session factory is alive. The second-level cache holds on to the ‘data’ for all properties and associations for individual entities that are marked to be cached. The second level cache is responsible for caching objects across sessions.

Cache Type
EHCache (Easy Hibernate Cache) — http://ehcache.sourceforge.net/
OSCache (Open Symphony) — http://www.opensymphony.com/oscache/
SwarmCache — http://swarmcache.sourceforge.net/
JBoss TreeCache — http://jboss.org/wiki/Wiki.jsp?page=JBossCache

EHCache -s an open source widely used java distributed cache for general purpose caching, Java EE and light-weight containers. It features memory and disk stores, replicate by copy and invalidate, listeners, cache loaders, cache extensions, cache exception handlers, a gzip caching servlet filter, RESTful and SOAP APIs and much more. Ehcache is available under an Apache open source license and is actively developed, maintained and supported.It support read only, Non strict Read/write,Read/write caching.It does not support transactional caching architecture.
OSCache – is “a Java framework” developed by OpenSymphony that makes it easy to cache content in Web applications.It is a caching solution that includes a JSP tag library and set of classes to perform fine grained dynamic caching of JSP content, servlet responses or arbitrary objects.It provides both in memory and persistent on disk caches.They can allow your site to have graceful error tolerance .It support read only, Non strict Read/write,Read/write caching.It does not support transactional schema caching architecture.
SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching. This type of cache is appropriate for applications that typically have many more read operations than write operations.It support read only, Non strict Read/write caching.It does not support ,Read/write and transactional caching architecture.It is is a cluster-based caching.
JBoss TreeCache – is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.

ref- http://www.devx.com/dbzone/Article/29685/1954
– http://javaexp.blogspot.com/2007/10/level2-caching-in-hibernate.html

pimp it