24 paź 2013

Thread pool : Callable, Runnable, Executors

package com.areo;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {

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

	private static void executorWithCallable() {

		ExecutorService pool = Executors.newFixedThreadPool(10);
		
		ArrayList<Future<Integer>> list 
			= new ArrayList<Future<Integer>>();
		
		for (int i = 0; i < 300; i++) {
			Future<Integer> submit = pool.submit(new MyCallable());
			list.add(submit);
		}
		
		//father results
		int result = 0;
		for (Future<Integer> future : list) {
			try {
				result += future.get();
			} catch (InterruptedException e) {
			} catch (ExecutionException e) {
			}
		}
		
		//result is 300
		System.out.println("Result: " + result);
		
	}

	private static void executorWithRunnable() {
		ExecutorService pool = Executors.newFixedThreadPool(10);
		
		for (int i = 0; i < 300; i++) {
			pool.execute(new MThread());
		}
		
		pool.shutdown();
	}

	//callable
	static class MyCallable implements Callable<Integer>{

		
		public Integer call() throws Exception {
			
			System.out.println("Calling!");
			return 1;
		}
		
	}
	
	//runnable
	static class MThread implements Runnable{

		public void run() {
			long id = Thread.currentThread().getId();
			System.out.println(String.format("Thread id = %d", id));
		}
		
	}
}

20 lis 2012

Guava - EventBus example

package com.areoit.guava.eventbus;

import org.junit.Test;
import static org.junit.Assert.assertEquals;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class EventBusIntegerEventsTests {
 
 private static final String EVENT_BUS_ID = "numbers";

 /**
  * Case:
  *  + one listener
  *  + listener subcribe for Integer event
  *  + listener subcribe for Number event
  *  + REMEMBER: Integer IS-A Number
  */
 @Test
 public void oneIntegerEventTwoSubscribingMethod() {
 
  IntegerListener listener = new IntegerListener();
  Integer integerEvent = Integer.MAX_VALUE;
  
  EventBus eventBus = new EventBus(EVENT_BUS_ID);
  eventBus.register(listener);  
  eventBus.post(integerEvent);
  
  //check event counters
  int integerCount 
   = listener.getIntegerEventCount();
  
  int numberCount 
   = listener.getNumberEventCount();
  
  assertEquals(1, integerCount);
  assertEquals(1, numberCount);
 }
 

 class IntegerListener  {

  private int integerEventCount = 0;
  private int numberEventCount = 0;
   
  @Subscribe
  public void onIntegerEvent(Integer event) {
   ++integerEventCount;
  }
  
  @Subscribe
  public void onNumberEvent(Number event) {
   ++numberEventCount;
  }

  public int getIntegerEventCount() {
   return integerEventCount;
  }

  public int getNumberEventCount() {
   return numberEventCount;
  }
 }
 
 
}

Guava - Functions + composition

public class FunctionsTests {
 
 @Test
 public void Functions_converter_example() {
  
  Function stringToInteger = new Function() {

   @Override
   public Integer apply(String input) {
    return Integer.valueOf(input);
   }
  };
  
  Function integerToLong = new Function\() {
   @Override
   public Long apply(Integer input) {
    return Long.valueOf(input.longValue());
   }
  };
  
  Function stringToLong 
   = Functions.compose(integerToLong, stringToInteger);
  
  Long actual = stringToLong.apply("5");
  Long expected = 5L;
  
  assertEquals(expected, actual);
 }
}

19 lis 2012

Guava - Joiner

import org.junit.Test;

import com.google.common.base.Joiner;

public class Collections {

 @Test
 public void Joiner_on_list_with_one_null_value() {
  
  String actual 
   = Joiner
    .on(",")
    .skipNulls()
    .join("one",null,"two");
  
  assertEquals("one,two", actual);
 }
 
 @Test
 public void Joiner_on_map() {
  
  Map map = new HashMap();
  map.put("k1", "v1");
  map.put("k2", "v2");

  String actual 
   = Joiner
    .on(",")
    .withKeyValueSeparator(" => ")
    .join(map);
  
  assertEquals("k1 => v1,k2 => v2", actual);
 }

}

14 lis 2010

Inner class

  1. Klasy inner nie mogą mieć czegokolwiek static!
  2. MyOuter mo = new MyOuter(); // gotta get an instance!
    MyOuter.MyInner inner = mo.new MyInner();
  3. Instancja poza Outer class przez instancje.new Inner()
  4. IInstancja z klasy Outer Inner() normalnnie
  5. Nie mozna tworzyc Inner w statycznych metodach outer!!
  6. this w metodach Inner class odności sie do obiektu Inner !
  7. Outer.this odnosi sie wiadomo ( z poziomu metod Inner)
  8. Modyfikatory przy class Inner{} => public,protected,private ,final,abstract,static,strictfp //jak normalny member klasy Outer!!
  9. Local method class może być instance tylko w tej metodzie!
  10. Local method class może dobrać sie do Outer private members!
  11. Local method class nie może dostać sie do zmiennych w tej metodzie(nie fianl)!
  12. Local method class może dostać sie do zmiennych fonal w tej metodzie!!
  13. Local method class może być zonaczona jako final!! ( tak jak zmienna lokalna ,zasady)
  14. Local method class w metodzie statycznej ma tylko dostęp do zmiennych statycznych!! i nie ma dostępy do zmiennych outerClass!!
  15. Pamiętaj średniku po definicji klasy anonymous!!
  16. Klasa anonymous raczej overriding method niż dodaje ( problem z widzeniem nowej innej metody)
  17. interface cannot be in method :(
  18. Anonymous class moze implements tylko 1 interfejs!!

13 lis 2010

Generics

  1. List oznacza każdą listę czegokolwiek
  2. List foo = new ArrayList();// bad!
  3. 1) List list = new ArrayList(); //OK
    2) List aList = new ArrayList();//OK
    3) List foo = new ArrayList(); //BAD
    4) List cList = new ArrayList();//BAD
    5) List bList = new ArrayList(); //OK
    6) List dList = new ArrayList(); //BAD

12 sie 2010

equal i hashCode

1. int hashcode() - jaki bukiet ?
2. boolean equals(Object ob)
3. sprawdzaj na początku instanceof!
4. nie używaj transient zmiennych w hashCode()

@Test
public void test1() {

NotEqualOverriding a = new NotEqualOverriding();
NotEqualOverriding b = new NotEqualOverriding();

a.equals(b); //wersja 1 z return false;
a.equals((Object)b); //wersja 2


}

class NotEqualOverriding{

/*Tylko overloading*/
boolean equals(NotEqualOverriding er){
return false;
}
/** -> zonk to jest overloading! */
// @Override

public boolean equals(Object obj) {
// dodaj na poczatku test is-A!!
System.out.println(" nadpisny equal");
return super.equals(obj);
}

@Override
public int hashCode() {
int hash = 7;
return hash;
}
}

16 lip 2010

Try, catch throwing Exception


@Test
public void testThrowing(){
try{ }catch(NumberFormatException ex){ }finally{ }
}

@Test
public void testThrowing2() throws Exception{
try{
throw new Exception(); //=> musi byc throws
}catch(NumberFormatException ex){
throw new Exception();
//int x =9; // unreachable exception!!!!!!!!
}finally{
/**
* Wypisze naewt jak jest w Main;
*/
System.out.println("finally"); //wypisze
}
}

14 lip 2010

Porównanie integerów


@Test
public void testone(){

//test1
Integer piec1= 5;
Integer piec2= 5;
assertTrue(piec1==piec2); //pass

//test2
Integer integer1 = new Integer(10);
Integer integer2 = new Integer(10);
assertFalse(integer1==integer2); //pass

//test3
Integer piec1001= 1000;
Integer piec1002= 1000;
assertTrue(piec1==piec2); //pass

}

11 lip 2010


class A{
public static void metoda(){}
public void metoda{}
}


Błąd bo te samy nazwy metod mimo ,że jedna jest static!

8 lip 2010

Autoboxing


//LEGAL
long l = 1000;
double d = 1000;

//NOT LEGAL
Long l1 = 1000; // error
Double d1 = 1000; // error


i

private static void wrap_byte(Byte b) {}
private static void wrap_short(Short s) {}
private static void wrap_char(Character c) {}
private static void wrap_int(Integer i) {}
private static void wrap_long(Long l) {}
private static void wrap_float(Float f) {}
private static void wrap_double(Double d) {}

private static void print() {
wrap_byte(10); // error
wrap_short(10); // error
wrap_char(10); // error
wrap_int(10);
wrap_long(10); // error
wrap_float(10); // error
wrap_double(10); // error
}

13 mar 2010

String haczyk


String s1 = "abc";
String s2 = "abc";
if(s1 == s2)
System.out.println(1); //true!!!!!


//zaś
String test2 = "abcd";
String test = new String("abcd");
/*to 2 różne referencje !!!!!!!*/

12 mar 2010

Static int


static int x = getValue();
static int y = 5;
static int z = getValue();

static int getValue() {
return y;
}

@Test
public void staticTest() {
prn("x=" + x);//x=0
prn("z=" + z);//z=5
}
  1. Z tego wychodzi ,że inicjalozowane jest z góry na dół!

Unreachable statement


@Test
public void unreachableTest() throws Exception {

int x = 7;

try {
x += x *= x;
prn(x);
} finally {
throw new Exception("sonk");
}
x=8;
}

  1. Poieważ x=8 nigdy nie zostanie wykonany!

Haczyki


enum INDEX{JEDEN,DWA,TRZY};
public void hello() {

int x[][] = new int[2][];
int x[0]={1,2}; //zonk :( compile error

int x[]={1,2,3};
int y= x[INDEX.DWA]; //zonk compile error!!!
}
  1. int a[]={1,2,}; //ok
  2. int a[]; a={1,2,3} //Compile error

Switch,case


@Test
public void swicz() {

//jako argument: byte, short, char, int i enum!
// NIE long ;(

//błąd nr 1
// wartość CASE jest większa niż typu !!!!
byte b = 10;
// switch(b){ case 150: break; }


//błąd nr 2
//zmienna jako CASEnie znana w czasie kompilacji
final int x = 7;
//sytuacja błędówa :D
final int y;
y = 7;
switch (y) {
case x: {
}
//! case y:{} // constant expr required!!!!!
}

//błąd nr 3 => powtarzajace się wartości case
// uwaga na obliecznia wartości case przez consty!
}

@Test
public void testDefaultInSwitch() {

/**
* WNOSIKI:
* 1) Jeśli istnieje case o wartości x to nei bedzie default
* 2) Jeśli nie istnieje case ... to bedzie default
* BEZ wezględu na miejsce!!!
*/
int x = 6;

switch (x) {
default: {
prn("Default");
break;
}
case 6: {
prn("6");
break;
}
}
/*WYNIK 6*/

/////////switch 2
x=5;
switch (x) {
default: {
prn("Default");
}
case 6: {
prn("6");
break;
}
}
/*WYNIK: Default 6*/
}

If &&,||,|,&


@Test
public void test1() {


//kwestia && i & w if
if(True("1") &&True("2") & True("3")){} // 1 2 3
if(False("1") &&True("2") & True("3")){} // 1 !!!!!!!!
if(True("1") &&False("2") & True("3")){} // 1 2 3
if(True("1") &&False("2") && True("3")){} // 1 2
if(False("1") & True("3")){} // 1 3

//kwestia || i |
if(True("1") || False("2")){}//1
if(True("1") | False("2")){}//1 2

if(False("1") ||False("2") && False("3")){} // 1 2
if(False("1") ||False("2") | False("3")){} // 1 2 2

}

public boolean True(String msg ){
System.out.println(msg);
return true;

}
public boolean False(String msg ){
System.out.println(msg);
return false;
}

9 mar 2010

Overriding i overloading

Following code fragment is given (Java 5):

1: class Human {
2:
Human getIt() {
3:
return this;
4:
}
5:
}
6:
7:
class Worker extends Human {
8:
// insert a single method here
9:
}

Which of the following methods would compile if inserted at line 8

Human getIt() { return this; }
Worker getIt() { return this; }
Object getIt() { return this; }
int getIt() { return 1; }
int getIt(int x) { return 1; }
Object getIt(int x) { return this; }