How to convert an image to icon

One day, you will be in need to convert your image to an icon so it can suit the favicon (Icon show near the title tab) in your web pages. Nowadays a lot of softwares or online sites allow to do this, free of charge! Among them there is http://iconverticons.com , the online version is free, but for local use you should pay :D

Now let’s take an example with our Duke image :

Duke Logo

Duke Logo

Now go to the online version of the previous site by clicking here!

After that, you upload this duke image and click convert, then you’ll get a lot of images and scrolling down the page, you’ll find the icon that you need (generally 32×32), you save it, and you add it as favicon to your web pages, Done! Duke favicon

Autowiring by name

Let’s take a concrete example :
Card interface

package com.javailable.beans;

//Marker interface
public interface Card {

}

IdCard class

package com.javailable.beans;

public class IdCard implements Card {

	private String cardNumber;

	
	
	public IdCard() {
		super();
	}

	public IdCard(String cardNumber) {
		super();
		this.cardNumber = cardNumber;
	}

	public String getCardNumber() {
		return cardNumber;
	}

	public void setCardNumber(String cardNumber) {
		this.cardNumber = cardNumber;
	}

	@Override
	public String toString() {
		return "IdCard [cardNumber=" + cardNumber + "]";
	}
	

}

Person class

package com.javailable.beans;

public class Person {

	private String name;
	private Card idCard; // Coding to an interface, works hand in hand with
							// Dependency Injection

	public Person() {
		super();
	}

	public Person(String name, Card idCard) {
		super();
		this.name = name;
		this.idCard = idCard;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Card getIdCard() {
		return idCard;
	}

	public void setIdCard(Card idCard) {
		this.idCard = idCard;
	}
}

Now let’s configure our bean in the bean configuration file ‘beans.xml’ in a way that’s the person’s idCard is autowired to an idCard bean reference:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="person" class="com.javailable.beans.Person" autowire="byName"/>
	<!-- 
		The bean referenced by person is a Person class, and that class contains a property whose name is 'idCard'
		which is the same name as the id of the bean below which is an Card implementation, Spring will then autowire it 
		for you, isn't it amazing
	
	 -->
	
	<bean id="idCard" class="com.javailable.beans.IdCard">
	    <property name="cardNumber" value="T256932"/>
	</bean>
</beans>

Running the following main method:

package com.javailable.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {

		ApplicationContext context = new ClassPathXmlApplicationContext(
				"beans.xml");
		Person person = (Person) context.getBean("person");

		System.out.println(person.getIdCard());
	}

}

Output:

IdCard [cardNumber=T256932]

You May want to use the classes and the bean configuration available here, paste them into your project, with spring dependencies required.

See also  : Other autowiring types

AutoWiring with XML

If you develop a really small application, you can write your bean configuration file and giving the references to other bean (wiring them) explicitly, and as the time goes, your application will grows significantly and you will be lost in your XML lenghty file. Fortunatly, Spring can autowire  your beans by itself, and actually, there is four kinds of autowiring :mrgreen: :

the four kinds of AutoWiring Spring provides
byName Attempts to match all properties’ bean with beans that have the same ID as the properties.
byType Attempts to match all properties’ bean with beans that have the same type as the properties.
constructor Tries to call a constructor of the autowired bean with beans whose types are assignable to the constructor arguments.
autodetect Spring tries to apply constructor autowiring, if it fails, it proceeds to a ‘bytype’ autowiring

Note that for autodetect autowiring, is a combination of constructor and bytype autowiring!

Spring logo

Inner Beans in Spring

Prerequisites

  • Favorite IDE
  • Dependencies : Spring 3.0 core jars [To work with the context and retrieve your bean from the container]

Introduction

Two essential elements are making the core of Spring, Dependency Injection and Aspect oriented programming, and the former is used in order to provide loose coupling between your applications objects, so if are trying to declare your beans in the bean configuration file, you would like that an instance of bean is not shared by other bean (that would be perfectly possible through constructor & Setter injection), so to avoid this case, you should consider using inner bean.

Example

Problem

Let’s say  that a Person, in an application have his Id card, we all know that’s it’s belong to one and only one person, so let’s consider the following classes:

package com.javailable.beans;

//Marker interface
public interface Card {

}

package com.javailable.beans;

public class IdCard implements Card {

	private String cardNumber;

	public IdCard() {
		super();
	}

	public IdCard(String cardNumber) {
		super();
		this.cardNumber = cardNumber;
	}

	public String getCardNumber() {
		return cardNumber;
	}

	public void setCardNumber(String cardNumber) {
		this.cardNumber = cardNumber;
	}

	@Override
	public String toString() {
		return "IdCard [cardNumber=" + cardNumber + "]";
	}

}

package com.javailable.beans;

public class Person {

	private String name;
	private Card idCard; // Coding to an interface, works hand in hand with
							// Dependency Injection

	public Person() {
		super();
	}

	public Person(String name, Card idCard) {
		super();
		this.name = name;
		this.idCard = idCard;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Card getIdCard() {
		return idCard;
	}

	public void setIdCard(Card idCard) {
		this.idCard = idCard;
	}

}

Now here is our Xml bean configuration ‘beans.xml’ to declare beans and their dependencies:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

      <bean id="myIdCard" class="com.javailable.beans.IdCard">
        <property name="cardNumber" value="T569836"/>
    </bean>

    <bean id="person" class="com.javailable.beans.Person">
    	<property name="name" value="ElZakaria" />
        <property name="idCard" ref="myIdCard"/> <!-- We reference to myIdCard bean -->
    </bean>

</beans>

Now, running our program :

package com.javailable.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {

		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

		Person person = (Person) context.getBean("person");

		System.out.println(  person.getName() + " with an id card : " +person.getIdCard());

	}

}

We got the following output:

ElZakaria with an id card : IdCard [cardNumber=T569836]

Nice, seems to work, now try to add another bean of person, and we will refer to the same idCard:

 <bean id="person2" class="com.javailable.beans.Person">
    	<property name="name" value="Foreigner" />
        <property name="idCard" ref="myIdCard"/> <!-- We reference to myIdCard bean -->
    </bean>

And now, add those two lines in your main method:

Person person2 = (Person) context.getBean("person2");

		System.out.println(  person2.getName() + " with an id card : " +person2.getIdCard());

Getting the result :

ElZakaria with an id card : IdCard [cardNumber=T569836]
Foreigner with an id card : IdCard [cardNumber=T569836]

We see here that two different instances, that is to say persons, have the same id Card, Weird, isn’t it?
To get rid of this big problem we should hide the myIdCard bean to be used by only one bean, so Inner beans comes to the table!

Solution

:idea: Now let’s modify our ‘beans.xml’ a way that myIdCard is used only by ElZakaria :P :

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="person" class="com.javailable.beans.Person">
		<property name="name" value="ElZakaria" />
		<property name="idCard">
			<!-- An inner bean, cannot be used by another person, YES! -->
			<bean class="com.javailable.beans.IdCard">
				<property name="cardNumber" value="T569836" />
			</bean>
		</property>
	</bean>

	<bean id="person2" class="com.javailable.beans.Person">
		<property name="name" value="Foreigner" />
		<property name="idCard">
			<bean class="com.javailable.beans.IdCard">
				<property name="cardNumber" value="Z777888" />
			</bean>
		</property>
	</bean>

</beans>

Running now the program, the problem is definitely solved 8-) :

ElZakaria with an id card : IdCard [cardNumber=T569836]
Foreigner with an id card : IdCard [cardNumber=Z777888]

Adding an id attribute to an inner bean is perfectly legal, but unnecessary anyway, because it cannot be referenced by any bean!

What are Atomic Variables?

Most of the time, you use a static variable shared by many threads, so you are in need to synchronized the code where it is used, like for instance a counter, that you need to be incremented by many threads at the same time, so if you do not synchronize the write, a data race problem is more likely to happen, so you insert a synchronzied block or do it on the method:

    public static int counter;
    public void increment(){
      synchronized(this){
         counter++;
      }
    }

This code is not efficient due to your need to acquire a lock each time you need to increment a single variable, so the solution is to use what we call an atomic variable, java.util.concurrent has two subpackages, named java.util.concurrent.atomic and java.util.concurrent.locks , the Latter one which interest us now, containing the following classes:

  • AtomicBoolean
  • AtomicInteger #1
  • AtomicIntegerArray
  • AtomicLong #2
  • AtomicLongArray
  • AtomicReference
  • AtomicReferenceArray

The classes marked with #n [1,2] are the most important classes and are the only that extend java.lang.Number, all the other classes extend directly the Object Class.

They both contain analogous methods, let’s some important one of AtomicInteger:

public AtomicInteger() Initializes and instance with a 0 value
public AtomicInteger(int initVal) same but with a initVal value
int get() get the actual value
void set(int val) Set the integer containt in the class
boolean CompareAnSet(int expect, int update) if the actual value is expect, set the value to update
int getAndDecrement()
int DecrementAndGet()
Get the value and increment and vice versa
int getAndAdd(int delta) Get the value and add the passed arguement
intValue, longValue, doubleValue, floatValue Self Explanotary.

Now let’s take an example of normal integer (not safe) and an AtomicInteger, and make them used by several threads at a time:

import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @author ElZakaria
 */
public class AtomicIntegerIncrementer {

    static AtomicInteger ai = new AtomicInteger();
    static Integer varInt = 0;

    static class ThreadNotSafe extends Thread {

        @Override
        public void run() {

            System.out.println("Normal Integer incremented " + varInt++);

        }
    }

    static class ThreadInt extends Thread {

        @Override
        public void run() {
            System.out.println("Atomic Integer incremented" + ai.incrementAndGet());
        }
    }

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            (new ThreadInt()).start();
            (new ThreadNotSafe()).start();
        }
    }
}

Printing the following output:

run:
Atomic Integer incremented1
Normal Integer incremented 0
Normal Integer incremented 1
Atomic Integer incremented2
Atomic Integer incremented3
Atomic Integer incremented4
Atomic Integer incremented5
Normal Integer incremented 2
Normal Integer incremented 3
Normal Integer incremented 4
Atomic Integer incremented6
Atomic Integer incremented7
Normal Integer incremented 5
Normal Integer incremented 6
Atomic Integer incremented8
Normal Integer incremented 7
Atomic Integer incremented9
Atomic Integer incremented10
Normal Integer incremented 8
Normal Integer incremented 9
BUILD SUCCESSFUL (total time: 0 seconds)

The last value of the normal integer is 9 (which should be 10 in normal conditions), but it is 10 for the atomic Integer which is thread safe without the overhead of synchronization because it implements it internally.

How to use CyclicBarrier

Well, if one day you wanted that some threads wait at predefined point, until all the other threads concerned reach it, you would consider to use the CyclicBarrier class, calling the await() method in a thread, makes that thread wait until the specified number of thread has called the same method, and besides, if you want, you can launch a thread after all threads walled await.
First, let’s see the CyclicBarrier class:

Important methods of the CyclicBarrier class
CyclicBarrier(int numThreads) Creates a new CyclicBarrier that will trip when the given number of parties (threads) are waiting upon it, and does not perform a predefined action when the barrier is tripped.
CyclicBarrier(int numThreads, Runnable BarrierAction) Same as previous, but launch the BarrierAction target when all threads called await
int await()
int await(long timeOut, TimeUnit unit)
makes that thread wait that others threads call it, so the numbers of threads are finally reached!
boolean isBroken() See if the barrier is broken, for example when a thread got interrupted, or timed out.
void reset() Reset the barrier, and make all the waiting threads throw an BorkenBarrierException

As usual, let’s make a concrete example, for example a training can be done only if 11 players join the team, so let’s make a Thread ‘Training’ that will be automatically started once the players (Thread ‘Player’) call await on the CyclicBarried object.

The Player class definition :


import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ElZakaria
 */
public class Player  extends Thread{

    private CyclicBarrier barrier;
    public Player(String name,CyclicBarrier barrier)
    {
        setName(name);
        this.barrier = barrier;
        this.start();

    }

    @Override
    public void run() {

        System.out.println(getName() + " joined the team.");
        try {
            barrier.await();
        } catch (InterruptedException ex) {
            Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BrokenBarrierException ex) {
            //If another thread got interrupted the barrier is then broken
            //You can check with the isBroken() of CyclicBarrier Class
            Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
        }
        //Other process that a  player Should do :D 

    }

}

The training class definition:

/**
 *
 * @author ElZakaria
 */
public class Training  extends Thread{

    @Override
    public void run() {
        System.out.println(" All required players are ready, the game can begin");

    }

}

The Entry point:

import java.util.concurrent.CyclicBarrier;

/**
 *
 * @author ElZakaria
 */
public class Temp {

      public static void main(String[] args) throws InterruptedException {

        //We need eleven players if you want to assemble a football team right?
        CyclicBarrier cyclicBarrier = new CyclicBarrier(11, new Training());

        for (int i = 1; i <= 11; i++) {
            new Player("player " + i, cyclicBarrier);
        }

    }
}

Output :

run:
player 1 joined the team.
player 2 joined the team.
player 5 joined the team.
player 3 joined the team.
player 10 joined the team.
player 4 joined the team.
player 8 joined the team.
player 6 joined the team.
player 7 joined the team.
player 9 joined the team.
player 11 joined the team.
 All required players are ready, the game can begin   #12
BUILD SUCCESSFUL (total time: 1 second)

#12 is called (due to the start method of Training) once all eleven threads called await(), so they continue their execution at the same time.

Exchange Data

How to use Exchanger

If you are looking at way to make your threads exchanging data between them, you are on the right topic. The Exchanger class is a synchronizer that allow two threads to communicate between them any sort of data, it contains only one method (overloaded with a timeout).

Consider two threads doing some chat, (Ah it makes me remember of old days :D), we can implement it as follows ::

public class First extends Thread {

    private Exchanger<String> exchanger;

    public First(String name, Exchanger<String> exchanger) {


        setName(name);
        this.exchanger = exchanger;
        this.start();
    }

    @Override
    public void run() {
        try {
            String reply = exchanger.exchange("Hello Dude, whatssup?");
            System.out.println("Second :  " + reply); //The exchange method block for the other thread's answer and returns it as String (Generics ;))
            reply = exchanger.exchange("I have an exam tomorrow, I gotta go");
            System.out.println("Second : "  + reply);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println("First is now disconnected :/");

    }
}

public class Second extends Thread {

    private Exchanger<String> exchanger;

    public Second(String name, Exchanger<String> exchanger) {


        setName(name);
        this.exchanger = exchanger;
        this.start();
    }

    @Override
    public void run() {
        try {
            String reply = exchanger.exchange("I'm really fine thanks, hope the same thing for u!");
            System.out.println("First :  " + reply); //The exchange method block for the other thread's answer and returns it as String (Generics ;))

            reply = exchanger.exchange("Oh what a luck, Im on holiday, Good luck anyway.");
            System.out.println("First : " + reply);

        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        System.out.println("Second is now disconnected :/");

    }
}
public class Temp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws InterruptedException {

        Exchanger exchanger = new Exchanger();
        
          new First("Elzakaria", exchanger);
          new Second("Foreigner", exchanger);
          




    }
}

How it works is really simple: calling the exchanger method make the thread wait until both of them have called the exchange() method, and then this method returns the reply (String here, but could be an Object) of the other thread :)

The output is :

run:
First :  Hello Dude, whatssup?
Second :  I'm really fine thanks, hope the same thing for u!
First : I have an exam tomorrow, I gotta go
Second : Oh what a luck, Im on holiday, Good luck anyway.
First is now disconnected :/
Second is now disconnected :/
BUILD SUCCESSFUL (total time: 0 seconds)

How to use Semaphore in a multi-threaded environment!

In this tutorial, you are going to learn how to synchronize your code with high abstraction level, without using explicitly the synchronized  keyword to acquire the monitor lock for the object.

If we take a look at the java.util.concurrent package, we will see the Semaphore class, and containing several useful methods, among them:

Important methods of the Semaphore class
Semaphore(int permits) Constructor to create semaphore objects with a given number of permits (the number of threads that can access a resource at a time.
Semaphore(int permits, boolean fair) same as previous, with fair to truly forcing to adept to First Came first Served.
void acquire()
void acquire(int permits)
Acquire a permit if available; otherwise, it blocks until a permit becomes available (can throw an InterruptedException)
void acquireInterruptibly() Same as previous , but cannot be interrupted while waiting for the lock
boolean tryAcquire()
boolean tryAcquire(long timeout, TimeUnit unit)
Non blocking method, if the permit is not available, immediately returns false
void release()
void release(int permits)
release the permit from the semaphore

Notice that the number passed to the constructor precise how much threads can access the critical section, thing you couldn’t do with a the synchronized code, which force only one thread at a time:

 synchronized(this)
 {

   //critical section
  }

Now, let’s take a concrete Example, let’s suppose an office that couldn’t be accessed by more than two persons, if a third person come to the office, He will wait until one of the 2 persons leave.

//Class representing a person
//Don't forget package and imports statement (java.util.concurrent.Semaphore)
public class Person extends Thread{
    private Semaphore semaphore;
    public Person(String name, Semaphore semaphore){
        this.setName(name);
        this.semaphore = semaphore;
        this.start();
    }
   @Override
    public void run(){
      System.out.println(getName() + " is trying to access the office.");
        try {
            semaphore.acquire(); //Is it free? ok, if it is no the case I will wait till it is.
            sleep(3000); //Let's simulate here the person is doing something
            // This person is done, let's release the lock
            System.out.println(getName() + " has just finished, and is going out from the office.");
            semaphore.release();
        } catch (InterruptedException exc) {
            exc.printStackTrace();
        }
    }

}
//Class containing the main method
public class Test{

public static void main(String[] args){
  Semaphore semaphore = new Semaphore(2); // Only two threads (representing person) at a time
  new Person("Elzakaria",semaphore);
  new Person("Anonymous",semaphore); //Notice the same semaphore will be used by the three threads
  new Person("Foreigner",semaphore);

}

}


Here is the output :

run:
Elzakaria is trying to access the office.
Elzakaria is actually in the office
Foreigner is trying to access the office.
Foreigner is actually in the office
Anonymous is trying to access the office.
Elzakaria has just finished, and is going out from the office.
Anonymous is actually in the office
Foreigner has just finished, and is going out from the office.
Anonymous has just finished, and is going out from the office.
BUILD SUCCESSFUL (total time: 6 seconds)

The output is really self-explanotary, you shouldn’t have any trouble to use the other methods described abvoe.

Discover what are Synchronizers!

If you have already synchronized your code, in order that only one thread at time can access the critical section, you definitely know that use low-level tasks such as Thread class, synchronized keyword are kind of cumbersome, in order to achieve a thread-safe code. Since java 5.0, the newly introduced package java.util.concurrent comes with High Abstraction so you deal only with few classes to achieve the same aim.

You will find the following classes useful for you, if work in a multi-threaded application :

Nested Classes [Details]

After reading the introduction to Nested classes, we will see all the flavors of nested classes!

Static nested classes

Static nested classes, are normal classes like any other top-level , the difference between them is that it is included in the middle of it, like the following:

    public class Outer{
       static int outerStatic = 7;
       int outerInstance = 8;

       public class Inner{ //You can put any modifier acces here, depending on your context
             static int innerStatic = 7;
              int innerInstance = 8;
              //methods + constructors, similar to normal classes.

       }
       public static void main(String[] args) {

          System.out.println(Outer.Inner.innerStatic); //#1
          System.out.println(Outer.Inner.innerInstance); //#2
          System.out.println(new Outer.Inner().innerInstance); //#3
          Outer.outerStatic++; //because of the hiding, otherwise you could only use outerStatic++ #4
       }

    }

In #1, we see how to access the static nested class, we have to only prefix it by the outer class name, that’s it, and innerStatic is accessible without an instance of inner, contrary to #2, the compiler will complain, because you need an instance of Inner (without an instance of Outer though), to access it, the correct code is in #3, where we instanciate Inner before using it.

A static inner class, can access all the static members of its outer class like in #4, but not the instance membes, because you do not have even an instance of the outer Object, you can use the this keyword inside inner code to reference the instance of Inner class, not Outer.

Inner Classes

Now, Inner classes are like static inner classes without the static keyword, that is to say, an inner class, is related to an instance of it’s outer class, we need an instance of the outer class in order to create an instance of the inner class, you can create it like the following:

  class Outer{
     class Inner{ //Also here, you can use any of the access modifiers, as Inner is a member of Outer.
         //all the members here
     }
  }

Behind the scenes, javac creates two byte code files, Outer.class and Outer$Inner.class.
The main difference with static inner class, is that an inner class CANNOT create static members.

Inner Class characteristics

Inner Class characteristics

Let’s see now how to create objects of Inner in your classes:

   Outer outerObj = new Outer();
   Outer.Inner innerObj = outerObj.new Inner();
   //Those two lines can be in one Outer.Inner inner = new Outer().new Inner(); but is a bit confusing isn't it?

Note the in the Inner class to refer to member of the Outer class, you use Outer.this reference, and to refers to the inner members, just use this.

Local Inner Classes

The third flavor, is the local inner class, which is defined in a method ( eventually static ):

   class Outer{
      private int a = 10;
       public void method(){
          class Inner{ // it is a local variable, so do not use any access modifier!!!!!
            //Declare what you  want, but no STATIC MEMBERS
            }
       }
   }

Also in this case, javac generates two files, Outer.class and Outer$1Inner.class, but we see an integer 1 here, because several methods in the same class can define a local inner class with the same name, the integer is here so we can differenciate between them. Note that you can access members of the outer class, including private members, except the static members.

I’ll not cover the anonymous Inner classes, as it is not really interesting.