background preloader

JAVA

Facebook Twitter

Design Patterns in Java Tutorial. Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time. This tutorial will take you through step by step approach and examples using Java while learning Design Pattern concepts. This reference has been prepared for the experienced developers to provide best solutions to certain problems faced during software development and for un-experienced developers to learn software design in an easy and faster way. Before you start proceeding with this tutorial, I'm making an assumption that you are already aware about basic java programming concepts.

Java Questions

CyclicBarrier. The java.util.concurrent.CyclicBarrier class is a synchronization mechanism that can synchronize threads progressing through some algorithm. In other words, it is a barrier that all threads must wait at, until all threads reach it, before any of the threads can continue. Here is a diagram illustrating that: The threads wait for each other by calling the await() method on the CyclicBarrier. Once N threads are waiting at the CyclicBarrier, all threads are released and can continue running. Creating a CyclicBarrier When you create a CyclicBarrier you specify how many threads are to wait at it, before releasing them. Here is how you create a CyclicBarrier: CyclicBarrier barrier = new CyclicBarrier(2); Waiting at a CyclicBarrier Here is how a thread waits at a CyclicBarrier: barrier.await(); You can also specify a timeout for the waiting thread.

Barrier.await(10, TimeUnit.SECONDS); The waiting threads waits at the CyclicBarrier until either: CyclicBarrier Action CyclicBarrier Example.

Unsafe

Java Cache. POI - EXCEL. JUnit. NIO. Java : different ways to filter a Collection - My name is Guido. Java : different ways to filter a Collection by Guido García on 29/10/2011 Imagine we have a simple Java class: And that you have a Collection of Person objects, such as the following one: How would you create a new Collection containing only men over 21? Use plain Java, like real men do Filtering by predicate The second option is what Commons Collections and Guava propose, and that I think should have been part of the Java core at least since Java 5.

It remembers me the visitor pattern. I find it very similar to Python’s filter() function, but more verbose due to Java’s nature. This way your code becomes cleaner, and you can combine fine-grained reusable predicates. JSR 335, Project Lambda and lambdaj JSR 335 (Lambda Expressions for the Java Programming Language) is part of JSR 337 (Java SE 8), which is scheduled for release in late 2012. If you can not wait and need to start using that kind of syntax today, I recommend the lambdaj library, it is not the same but it is handy in some cases: Java Reflection (parte 1) - Blog - Arume. Una de las funcionalidades más potentes y poco conocidas de Java es su soporte para reflexión. Mediante la Java Reflection API el programador puede inspeccionar y manipular clases e interfaces (así como sus métodos y campos) en tiempo de ejecución, sin conocer a priori (en tiempo de compilación) los tipos y/o nombres de las clases específicas con las que está trabajando.

Quizás pueda parecernos en una primera impresión una funcionalidad con usos limitados. Pero debemos saber que, por ejemplo, muchos frameworks de alto nivel como Hibernate, Spring o Tapestry hacen un uso extensivo de esta API para facilitarle la vida al programador al permitirle que use simples clases POJO para trabajar con ellas. Clase Cuando en nuestro programa queremos usar reflexión para poder trabajar con un objeto del que desconocemos su tipo (en el caso de Java, esto es lo mismo que decir que desconocemos el nombre de su clase), lo primero que debemos hacer es averiguar la clase a la que pertenece. Constructores. Clases de Utilidad Java VII: Reflection | Un poco de Java. Bueno, pues vamos a avanzar un poco más en nuestras clases de utilidad y hoy vamos a poner unos cuantos métodos con los que poder usar el API reflection.

Éste API es muy usado dentro de la comunidad y es una herramienta muy potente a la hora de invocar métodos o clases por ejemplo definidos en base de datos. Obtener una clase a partir de un nombre: * Obtiene una clase a partir del nombre de la misma. * @param clazz La cadena que identifica la clase que se quiere obtener. * @return La clase correspondiente si se ha encontrado, y sino una excepción PLNException. * @throws La excepción Exception.

@SuppressWarnings("unchecked") public static Class getClass (String clazz) throws Exception { Class result = null; try { result = Class.forName(clazz); } catch (ClassNotFoundException e) { log.error("No se encuentra la clase " + clazz, e); throw new Exception("No se encuentra la clase " + clazz,e); } catch (NullPointerException e) { log.error("Se ha pasado un nombre de clase null ", e); return result; int i = 0; Java concurrency (multi-threading) - tutorial. Asynchronous task handling is important for any application which performs time consuming activities, as IO operations. Two basic approaches to asynchronous task handling are available to a Java application: application logic blocks until a task completesapplication logic is called once the task completes, this is called a nonblocking approach.

CompletableFuture extends the functionality of the Future interface for asynchronous calls. It also implements the CompletionStage interface. It adds standard techniques for executing application code when a task completes, including various ways to combine tasks. This callback can be executed in another thread as the thread in which the CompletableFuture is executed. The following example demonstrates how to create a basic CompletableFuture. CompletableFuture.supplyAsync(this::doSomething); CompletableFuture.supplyAsync runs the task asynchronously on the default thread pool of Java.

Keytool

Guava. Upgrade from Tiles 2 to Tiles 3 on Spring MVC 3 application | Codingpedia.org. I’ve just upgraded the web application that powers Podcastpedia.org to use Apache Tiles 3 instead of Tiles 2. I am particularly interested in the Tiles integration with Velocity for email generation. Note: You need at least the Spring 3.2 release for this to work. This occured in three small steps: upgrade maven dependenciesupgrade tiles elements in the Spring application contextupgrade tiles dtd version 1. What I had to do was just replace the ${tiles.version} in the maven pom.xml file from 2.2.2 to 3.0.1 for the Tiles dependencies I use, and now it looks like this: 2.

The next thing was to upgrade to version 3 the tilesViewResolver and tilesConfigurer in the Spring application context: Tiles configuration in the Spring application context .................... <! 3. In the Tiles definitions templates upgrade to Tiles 3.0 dtd <? That’s it. P.S. Design Patterns in Java Tutorial. Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development.

These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time. This tutorial will take you through step by step approach and examples using Java while learning Design Pattern concepts. This reference has been prepared for the experienced developers to provide best solutions to certain problems faced during software development and for un-experienced developers to learn software design in an easy and faster way. Before you start proceeding with this tutorial, I'm making an assumption that you are already aware about basic java programming concepts. If you are not well aware of these concepts then I will suggest to go through our short tutorial on Java Programming.

Struts 2

Play framework - Home. Java Weak Reference. Releasing unused objects for garbage collection can be done efficiently using java weak reference. Yes. weak reference is related to garbage collection. In java we need to not anything explicitly for garbage collection (GC), this memory management overhead is taken care by java run-time itself. Then what is the use of java weak reference? Let us see an example scenario, which will help us understand the problem in detail.

Before that, we should be aware there are four types of references in java and they are strong reference, weak reference, soft reference and phantom reference. Weak Reference When there are one or more reference to an object it will not be garbage collected in Java. Let us take a sample scenario to understand it better.

Key is TextView object and value is the Id. So, programmatic we need to ensure that, when a textView is removed then its corresponding entry in the map should be removed. WeakHashMap There is a predefined Map which uses weak reference. Soft Reference. JBoss AS Storage Hints - jboss configuration.

EJBs

Retrieve Oracle version information. This Oracle tutorial explains how to find the Oracle version information with syntax and examples. Description You can check the Oracle version by running a query from the command prompt. The version information is stored in a table called v$version. In this table you can find the version information for Oracle, PL/SQL, etc. Syntax The syntax to retrieve the Oracle version information is: SELECT * FROM v$version; SELECT * FROM v$version WHERE banner LIKE 'Oracle%'; Parameters or Arguments There are no parameters or arguments. Example Let's look at some of examples of how to retrieve version information from Oracle. All Version Information To retrieve all version information from Oracle, you could execute the following SQL statement: This query would output something like this: Oracle Version Only If you only wanted the Oracle version information, you execute the following SQL statement: It should return something like this:

SLF4J. Java - Using Jpcap to create JAVA applications that capture network traffic. Jpcap network packet capture library. Network Packet Capture Facility for Java | Free software downloads. Kaitoy/pcap4j. Programación con Java: 10 de las Mejores Prácticas en Java. 1.- Evitar la creación innecesaria de objetos, Lazy Initialitation La creación de objetos en Java es una de las operaciones mas costosas en términos de uso de memoria e impacto en el performance. Esto es evitable creando o inicializando objetos solo en el momento en que serán requeridos en el código. public class Paises { private List paises; public List getPaises() { //se inicializa solo cuando es requerido if(null == paises) { paises = new ArrayList(); } return paises; } } 2.- Nunca hacer variables de instancia públicas Hacer una clase publica se puede ocasionar problemas en un programa.

Public class MiCalendario { public String[] diasDeLaSemana = {"Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"}; //mas código } La mejor práctica es como mucho de ustedes saben, es siempre definir estas variables como privadas y crear los métodos accesores, “setters“ y “getters” Pero escribir los métodos accesores no resuelve el problema del todo. Escribir código es divertido.

Buenas prácticas para la construcción de software. Your Source for Java Information.