avr

23

Java generalities

Posted by : admin | On : 23 avril 2012

Source

http://www.careerride.com/Spring-bean-lifecycle-in-spring-framework.aspx

Question/response  JAVA

Spring

What is Spring?

Spring is a framework that resolves common problems in JEE architecture. (JDBC ,integration later, presentation layer …)
Spring is managing business objects and encouraging practices POJO model (vs programming model)
It’s highly recommended to use a architectural tiers  (presentation,business,dao Layer) ; the inejection of the different beans is realized by utilizing IoC.
Spring is both comprehensive and modular. Spring has a layered architecture, meaning that you can choose to use just about any part of it in isolation. Spring is also an ideal framework for test driven projects.

  • The most common modules are :
  1. Most use module : Spring core, Spring test, Spring jdbc
  2. Advanced module :  Spring AOP ,Spring integration , Spring batch

Bean lifecycle in Spring framework.

The bean’s definition is found by the spring container from the XML file and instantiates the bean.

All the properties specified in the bean definition are populated by spring using dependency injection.

 

The bean’s Id is passed to setBeanName() method by the factory, and the factory calls setBeanFactory() is passed to itself, incase the bean implements the BeanFactoryAware interface.

The init() method is invoked if specified. If any BeanPostProcessors are associated with the bean, the methods postProcessAfterInitialization() are invoked.

Thread in JAVA

http://www.careerride.com/Interview-Questions-Java-Threading.aspx

2 type of process are being execute in a PC

les multitache  par processus + long pour le CPU de réaliser le swap entre les différents applicatif .

Le multitache par thread

class MonThread implements Runnable {
	Thread t ;
	MonThread("Mon thread "){
		t = new Thread("Mon thread");
		t.start();
	}
	public void run(){
		System.out.println("Thread enfant démarré");
	}

	public static void main(String args[]){
		new MonThread();
		System.out.println("Thread principale démarré ");
		System.out.println("Thread principale terminé ");
	}
}

l’instruction join() permet d’attendre le thread enfant se termine et qu’il rejoinne le thread principale . (exemple le thread du main)

permettre à deux thread de ne pas accéder à la même ressource en même temps on utilise pour cela le mot clé synchronized dans le prototype de la méthode.Souvent cela arrive lorsque 1 thread => appel 1 methode d’une autre classe Exemple :

class  MonThread implements Runnable (){
	String s1 ;
	Parenthese p1;
	Thread t ;
	public MonThread(Parenthese p2 , String s2){
		p1 = p2 ;
		s1 = s2 ;
		t = new Thread(this);
		t.start();
	}
	public void run(){
		p1.afficher(); // La méthode affficher doit être nécessairement en synchronized
	}
}

Une méthode peut etre appellé à l’intérieur d’un bloc synchronizé ( les objets et les methodes sont synchronisés ) Les appels aux méthodes contenues dans le bloc synchronisé n’ont lieu qu’après que le threade a activé le moniteur sur objet L’instruction synchronized

 

public void run(){
	synchronized(p1){
		p1.afficher();
	}
}

 

Communication entre les threads wait() demande à un thread de libérer un moniteur et de se placer en suspens .notify() demande au thread suspendu de se remettre en marche et de reprendre le contrôle du moniteur

 

class MonThread implements Runnable {
	Thread t;

	MonThread(String threadName) {
		// t = new Thread(threadName);
		// t.start();
	}

	public void run() {
		System.out.println("RUN Child thread :" + Thread.currentThread());
	}

	public static void main(String args[]) throws InterruptedException {
		Thread thread1 = new Thread(new MonThread("thread1"), "thread1");
		Thread thread2 = new Thread(new MonThread("thread2"), "thread2");
		thread1.start();
		thread2.start();

		thread1.join();
		if (!thread1.isAlive()) {
			System.out.println("Thread T1 is not alive.");
		}
		thread2.join();
		if (!thread2.isAlive())
			System.out.println("Thread T2 is not alive.");

		Thread.currentThread().sleep(2000);
		System.out.println(Thread.currentThread());

	}
}

RUN Child thread :Thread[thread1,5,main]

RUN Child thread :Thread[thread2,5,main]

Thread T1 is not alive.Thread T2 is not alive.

Thread[main,5,main]

package coordination;

public class AutoBus extends Thread {
	int total = 0;

	public void run() {
		synchronized (this) {
			System.out.println("wait ...");
			for (int i = 0; i < 100; i++)
				total = +i;
			System.out.println("passenger is given notification call ");
			notify();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		AutoBus bus = new AutoBus();
		bus.start();
		synchronized (bus) {
			System.out.println(" passenger is waiting for the bus");
			bus.wait();
			System.out.println("passenger go notification");
		}
		System.out.println(" total=" + bus.total);
	}
}

passenger is waiting for the buswait …

passenger is given notification call passenger go notification total=99

Example questions :

how to create a thread and start it running
Example 1 : Extending Thread Class

Example 2 : implentation Runnable

Explain how do we allow one thread to wait while other to finish.

When a thread is created and started, what is its initial state?
Ready for execution (Create + started )
A thread is in “Ready” state after it has been created and started.
This state signifies that the thread is ready for execution. From here, it can be in the running state.

explain monitor in java

mot clé synchronization

What is serializable Interface?

If we want to transfer data over a network then it needs to be serialized. Objects cannot be transferred as they are. Hence, we need to declare that a class implements serializable so that a compiler knows that the data needs to be serialized.

 

 

EJB

EJB is a standard for developing server side in JAVA. It specifies agreement between components and application servers that allows components to run on server. They are mainly for complex serer side operations like executing complex algorithm or high volume business. EJB provides the application layer logic, also called as middle tier. It provides a standard specifications-based way to develop and deploy enterprise-class system.

What are the kinds of EJB’s?

There are 3 kinds of EJB’s -

  1. Session beans,
  2. Entity Beans
  3. Message-driven beans

 

  • Session beans

Sessions beans represent business logic of an application. Session beans can be of 2 types namely stateless and stateful beans

  • Entity Beans

Entity beans represent persistent data in an EJB application.

  • Message-driven beans

This type of beans is used implement asynchronous communication in the system.

Stateful

The state of the conversation can be maintained using a stateful session bean.
It implements ‘javax.ejb.SessionBean’ interface and is deployed with the declarative attribute ‘stateful’.
The instance variables contain a state only during the invocation by a client method.
The bean can use the conversational states as its business process methods.

Main cons: Resources that is needed to be substain to maintain connection between server and client
Other discussion pro/cons :

http://blog.xebia.fr/2007/07/24/service-stateful-vs-service-stateless/

Stateless

We dont maintain conversational state specific to client session.
It is an EJB component that implements ‘javax.ejb.SessionBean’ interface.
The stateless session bens carry equal value for all the instances due to which a container can assign a bean to any client making it very scalable.
There is no instance state. The business methods on a stateless session bean are like procedural applications or static methods, so all the data needed to execute the method is provided by the method arguments.
Stateless session beans are very lightweight and fast.Typically an application requires less number of stateless beans compared to stateful beans.

What is lazy loading?

Heavy weight application consume a lot of time while loading the plug-ins. In lazy loading approach, the plug-ins that are needed at that particular time are loaded and instantiated. This boosts up the performance as only the plug-ins that are used are loaded. This also ensures the efficiency and speeds up the initial load time of the applications. Applications like Eclipse use this approach. In other words, the goal of lazy loading is to dedicate memory only when it is absolutely necessary.

Difference between a Server, a Container, and a Connector?

-A server is an application that responds to the requests made by client(s) and manages system resources like network connections, threads, processes, memory, database connections, etc
E.g.: Websphere,Jonas,BEA WebLogic …
-A server can contain N number of containers. An EJB container runs inside an EJB server. The Container shields the EJB server through an API between the bean and its container.
-A connector is used to resolve the issue with the legacy systems. A connector is an architecture defined by Sun. Since the applications running on the legacy systems cannot be discarded due to the business logic and other reasons, the connectors were used to serve the purpose.
(exemple connector : Oracle, Mysql,Postgre …)

 

Packaging :

What is the difference between EAR, JAR and WAR file?

Modules are packaged based on their functionality as EAR, JAR and WAR files.

• JAR files (.jar):Modules which contain EJB class files and EJB deployment descriptor are packed as JAR files.
WAR Files (.war):Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as JAR file.
EAR Files (.ear):‘.jar’ & ‘.war’ files are packaged as JAR files. ‘Ear’ stands for enterprise archive. These files are deployed in the application server.

 

Révision Java

Variables en Java

  • Variable instance ont pour durée de vie celle de l’objet
  • Variable de classe sont mis en place quand les classes sont dites chargées .
  • Variable locales celle d’une fonction

 

Flux

Java.io

Flux entrée System.in .

Remarque : Depuis Java 5 la classe Scanner permet de lire les entrées clavier facilement

Scanner scanner = new Scanner(System.in);

String choix = scanner.next();

Flux de sortie : System.out

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

nom = br.readLine();

 

mot clé static

on peut appeler la méthode d’un objet sans avoir à instancier celui ci

On l’utilise le plus souvent lorsque l’objet n’a pas de rapport à proprement dit avec la classe

disposer d’information collectives (exemple : comptage instance de classe )

ou bien disposer de fonction indépendante

 

bloc static

n’ont accès qu’au champs static de la classe

utilise surtout pour initialiser des champs static

=> Conseil mieux vaut avoir un private static methode pour avoir la main sur nos variables facilement

 

Clonage

recopie les références de l’objet mais ne provoquue pas la recopie des valeur des objets .

 

compare

== et !=

ne compare les objets que sur les reférences , peut être utilisé pour comparer des références null , 2 énum values …

a.compareTo(b) compare les values des champs a et b et retourne un int issu de la comparaison

=> penser aussi au pattern Iterator et à la classe Comparator<T>

 

La rammasse miette en java

Lors un objet ne possède plus de référence sur cet objet on dit qu’il est candidat au gargage collector

finalize() est appellé par le garbage collector quand la condition précédente est vérifié

 

Classe anonymes

permet de définir une classe sans lui donner de nom

pas de référence possible

classe anonyme peut dériver d’une autre classe (exemple de la classe JpaTemplate )

classe anonyme implémentant une interface

 

Héritage

le constructeur dérivée (fille) doit prendre en charge l’intégralité de la contruction du père.

ou bien utiliser le mot clé super() pour ne pas avoir à redéfinir les fonctionnalités et disposé de celle défini dans la classe mère.

 

Polymorphisme

complète l’héritage , peut prendre plusieurs formes ou comportement suivant les situations .

différentes formes de polymorphisme

méthode

classe

polymorphisme via heritage (on spécialise un comportement )

String … elements <=> String [] elements

 

final

interdit la modification de la valeur (variable )

méthode final ne peuvent être redéfini par une classe dérivée

classe final idem

 

classe abstraites

pas instancation objet possible

contient les méthodes et champs dont héritera toutes les classes dérivées

 

Exception

des erreur peuvent se produire on les gère… gestion des exceptions

Java.lang.Throwable

|

exception                                  java.lang.error

Runtime      SQLException/IOException

NPE

SeccurityException

 

Manipulation des chaines de caractères

StringBuffer

StringTokenizer

matcher

Java 5

  • prommation générique
  • annotation
  • autoboxing /unboxing (conversion auto des types )
  • énumération
  • nouvelles classes (scanner , formatter …)
  • Java concurrency

 

 

Collection en Java

  • Vecteur : ensemble objet pouvant être retrouvé par leur référence
  • Liste : ensemble objet classé par leur position
  • Ensembles : ensemble objet classé par leur type
  • Table de hashage :  ensemble objet classé à l’aide d’une clé
  • Pile : ensemble objet classé pouvant être simplement posé ou retiré

List

doublon autorisé

récupération via index

LinkedList (liste doublement chainée )

ArrayList (tableau redimensionnable)

Vector ( la différence avec ArrayList est qu’elle est synchronisé durant l’appel de la méthode de cette classe par un thread autre et ne peut être modifier )

 

Map

clé /valeur

unicité de la clé

HashTable va recherche ses éléments avec hashCode

HashTable est ThreadSafe et n’accepte pas null

 

HashMap n’est poas ThreadSafe

 

Set

n’accepte pas les doublons

HahsSet permet de stocker des objets sans doublons , n’accepte pas d’objet null (sinon NPE) => Iterator

 

TreeSet utilise un arbre de recherche

SortedSet

 

Pile

pop/push

 

Iterator

List<String> maListe = new ArrayList<String>();

maListe.add(« Bonkour »);

Iterator<String> it= maListe.iterator();

while(it.hasNext()){

sysout(it.next());

}

parcours HashMap

for(Key key : map.keySet()){}

 

SQL

inner join

relation 1-1 entre 2 tables

exemple :

Select * from Employee inner join departement on employee.DepartementID=departement.DepartementID

natural join : jointure faites sur les tables de même nom

Left / right join (favoriser une ou autre des tables)

Toutes les valeur de  A et les valeurs de B qui matche avec A

cela se traduit en clair quelquesoit ….. who is in

 

Laisser un commentaire

Your email address will not be published. Required fields are marked *