Thursday 18 June 2015

JTA bean-managed transaction. Why?

Bean-managed transaction (BMT), also known as programatic transactions are implemented with the
help of javax.transaction.UserTransaction inteface, which have the commit(), the begin(), the rollback() methods, Why we need it? There are 3 possible reasons:

  1. We want to use a transaction not in EJB beans (we can use it in POJO or CDI bean)
  2. We want a one transaction during several request.
  3. We want client-initiated Transactions: a client, such as an applet, can obtain a reference to the UserTransaction and TransactionManager objects using JNDI. A client can begin a transaction using either object reference

Sunday 11 January 2015

SCJP notes: Strings, StringBuffer and StringBuilder

Strings
  • String are immutable objects, so when you trying to change it like: "s.concat("bla")" - you not changing the current object, you creating the new one
  • This statement String s = "dsfsf" creates new String literal in the run time constant pool and even if the reference for this literal is lost it still will exist (the most likely) in memory
  • This statement String s = new String ("dsfsf") will create two objects: one on the heap and second in the run time constant pool there is such String. And the variable will be reference to the String in the heap
  • If call the intern() method it will return the reference to the same String in  the run time constant pool, if there is no such string there it will create it
  • For Strings we can use the +=  operator to concatenation and assign in a one line
  • Important String methods: charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toString(), toUpperCase(), trim() 
  • If you ask charAt() with the index more than letters in the word-1(indexes starts with 0), you will get StringIndexOutOfBoundsException
  • If you ask substring() with the index more than letters in the word-1(indexes starts with 0), you won't get an exception, you will get an empty String
StringBuffer and StringBuilder

  • StringBuffer is StringBuilder
  • Important StringBuffer and StringBuilder methods: append(), delete(), insert(), reverse(), toString()
  • Almost all mentioned methods(except toString) returns the modified StringBuffer and StringBuilder object, but in comparison with String this methods change the object on which this methods will be called

Saturday 10 January 2015

SCJP notes: multithreading


Miscelanious
  • If you want to write the code that will be started in its own thread, you can: or implement the Runnable interface; or extend the Thread object
  • To start the code to run its own thread, just call the start() method (not the run())
  • Thread itself implements Runnable
  • If you will to start already started Thread you will get IllegalThreadStateException
  • There is now way to pass the Thread priority, to the Threads constructor, you can pass only the thread name
  • To pass the priority to the thread just use the setPriority() method
  • Thread priority could be from 1 to 10
  • Priorities could be ignored by JVM
  • If priority of started Thread wasn't specified, the priority would be inherited from the priority of the Thread that stated Thread
java.lang.Thread important methods
  • To get the current thread instance you should call the Thread.getCurrentThread() method
  • The static Thread.sleep() method throws checked InterruptedException when thread encounters sleep it must go to sleep for at least to the number of specified milliseconds
  • The static Thread.yeld() method could be used as the hint to the scheduler that the current thread is willing to yield its current use of a processor and if it was successful in it other thread will run. But it is absolutely not guarunteed
  • The non-static join() method  throws checked InterruptedException makes the current thread wait until the Thread on which instance it was called will finish its work. If Thread on which instance it was called wasn't started or already dead nothing happens
  • The non-static interrupt() method if interrupted thread in the sleeping or waiting state cause the sleeping thread throw InterruptedException. Else just change the flag isInterrupted() to true. . Possible to interrupt not started thread and then start it. The isInterrupted() method will return false
  • The non-static setDaemon() method, sets the method as daemon. Program won't wait this thread to be finished
Synchronization
  • The method or the block of code could be synchronized and you need to synchronize when there is more than two thread in your application trying to access the same the data and at least one thread modifies this data
  • Synchronizing the instance method will cause the synchronization only for this one instance
  • The static method or the block of code could be synchronized on the static variable, so only one thread for the all application could execute such code at once
  • Synchronization of the non-static getter or setter for the static field will ensure you from race condition only when you use only one instance. When there is two or more instances synchronization could be broken
  • Synchronization of the static and non-methods doesn’t block each other
  • Sleep doesn't release the synchronization lock
  • The all run() method could be syncromized
 java.lang.Object important methods
  • wait(), notify(), notifyAll() must be called from within a synchronized context! A thread can't invoke this method on an object unless its own that object's lock. You will get the IllegalMonitorStateException if you will try it
  • The non-static wait() method  throws checked InterruptedException release the lock of synchronization and makes the thread to waits until it will notified or interrupted, or until timeout is passed if it is specified
  • There is  possibility that the thread will spontaneously wakes up it is so called "spurious wake ups"
  • The non-static method notify() wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is randomly chosen to be awakened. If nobody waits this monitor - nothing happens

Tuesday 6 January 2015

SCJP notes: innner classes

"Regular" inner classes
  • The inner class couldn't have anything static, except compile-time constants
  • The inner class doesn't initialized when the outer is initialized
  • The inner class could have every possible access modifiers
  • Actually, inner class could have all modifiers (like: strictfp, final, abstract)
  • The only way you can access the inner class is through a live instance of the outer class
  • So you couldn't instantiate the inner class in static method of the outer class(unless you create there an instance of the outer class)
  • The inner class as a member of the outer class has the access to all other members of the outer class
  • To instantiate the inner class inside outer, just write new Inner()
  • To instantiate the inner class outside outer, you need to write something like: new Outer().new Inner()
  • You can get the link to the outer class that corresponds to the inner by Outer.this
  • You can get the link to the inner class inside inner by this or Outer.Inner.this
  • You couldn't instantiate static member in the inner class
  • But you could inherit them from other class
Method-local inner class
  • The instantiation of the method-local inner class should go after its declaration
  • The instantiation of the method-local inner class could be done only inside the method where it is declared
  • As "regular" inner class has access to all outer class members
  • The method-local inner class could use only final local variables
  • The method-local inner class could have the following modifiers: strictfp, final, abstract
  • The method-local inner class could be declared in the static method, but in this case it will have access only to the static members of the outer class, and no any "this" will be available
  • As "regular" inner classes method-local inner class couldn't declare static content
Anonymous inner class
  • There could be new methods in the anonymous inner class, but there will be no way (except reflection) to call them
  • You couldn't define new constructor within the anonymous inner class
  • You could use the proper constructor by the anonymous inner class
  • As "regular" inner classes method-local inner class couldn't declare static content
  • As the method-local inner class could use only final local variables, so it is just method-local inner class
  • As "regular" inner class has access to all outer class members
  • Anonymous inner class allows you to create the interface implementer
  • You can pass the anonymous inner class as the method parameter
Static nested classes
  • The static nested class has the access only to the static members of the outer class
  • Could declare the own static members
  • You do not need the instance of the outer class, actually even when you have you couldn't create the instance of the static inner with the instance of the outer class. The only way to create instance of staitc nested class looks like: Outer.Inner inner = new Outer.Inner();




Monday 5 January 2015

SCJP notes: collections and generics

Miscellaneous

  • Most of collections classes are not final, so they could be subclassed

Maps:
  • Map doesn't implement Collection
  • Map doesn't have the contains() as all collections, but it has containsKey() and containsValue()  methods
  • Map implementations: TreeMap, Hashtable, HashMap. LinkedHashMap
  • LinkedHashMap extends HashMap is ordered Map
  • Hashtable is HashMap with synchronized methods
  • Hashtable, HashMap  not sorted and not ordered
  • HashMap allows null as key, all other implementation will throw nullpointer, when you try to add it
  • When you add duplicate in map, it replace previous value
  • For Map sometimes it is critical to override equals and hashcode to get your value back from Map
  • If you will try to add to the TreeMap something that is not Comparable, you will get at this time ClassCastException
  • Or you can supply to the TreeMap constructor the comparator, to avoid previously mentioned exception.
  • If you want to iterate throw Map, you need to call the entrySet() method, and then can call iterator from it. Map itself doesn't have the iterator
Sets:
  • Set implementations: TreeSet, HashSet, LinkedHashSet
  • Couldn't get element by index, need iterator or for-each construction
Navigating TreeMaps and TreeSets:
  • TreeMaps and TreeSets are sorted in natural ascending order 
  • TreeMap has methods like: higherKey(), lowerKey(), floorKey(), ceilingKey()
  • TreeSet has methods like: higher(), lower(), floor(), ceiling()
  • higherXXX() returns the element is smaller than the asked one
  • ceilingKeyXXX()  returns the element is smaller or equals that the asked one
  • TreeMap and TreeSet has descendingXXX() method
  • TreeSet hass pollFirst() and pollLast() methods that returnas and removes from the collection the first or last items
  • For TreeMap the same, but just pollFirstEntry() or pollLastEntry() 
Lists:
  • List implementations: ArrayList, LinkedList, Vector
  • LinkedList implemenst the Queue inteface
  • The add(<something to add>) method adds to the end of the list 
  • Or the add(int index, <something to add>) method  adds to the specified index position and moves all element with index higher or equals of specified index.
  • The set(int index, <something to add>) method replace existing value by index, could get IndexOutOfBoundsException if there is no such value by index that should be replaced
  • The sublist method returns the baked sublist with left borde inclusive and right border exclusive, you can also specify both borders with the same value, it will return empty list
Queues:
  • Queue implementations: LinkedList, PriorityQueue
  • PriorityQueue just sorted queue
  • Queue inteface and so on PriorityQueue has method offer() that is used to add something to the queue, and no methods as offerFirst() and offerLast() 
  • LinkedList has the offerFirst() and offerLast() methods
Backed collections
  • Everything that implements collection (everything except maps) has toArray() methods
  • The first of toArray() takes nothing and returns the array of Object
  • The second of toArray() takes the array of the type of the generics Collection, returns this array populated with the Collection items if the capacity of this array is enough, and new array of the same type if no.
  • This array is not backed with the Collection from which it was derived
  • If you will try to derive the list from the array of primitives you will get the list of arrays of these primitives.
  • Arrays.asList() return the generic list of the type of the passed array, backed together. Backed means that the list will be fixed size (you will get exception trying to add something), but if you change something in this collection the array will know about it, and the vice versa.
Sorting and searching throw collections and arrays
  • Collections (only for Lists) and Arrays classes has the sort() method that has two flavors: the first takes Comparable Collection; the second takes Collection and Comparator
  • Both Comparable and Comparator could be parameterized by generics
  • Collections (only for Lists) and Arrays classes has the binarySearch() method, this method searches throw sorted List or array and returns the index of the element if it was found
  • If the searched List or array wasn’t sorted the result of the search in unpredictable
  • If the searched List or array doesn't contains the searched element it will return the index where this element could be added with no braking sort - 1
  • Collections has the reverseOrder() method which takes Comparator and returns the reverse order Comparator
  • Collections has the reverseOrder() method which takes nothing and returns the reverse order Comparator for all Comparable objects, but if you try to sort or search with this Comparator something that is not Comparable you will get ClassCastException
  • During binary search, if one object equals another one will be taken not from equals() method, but from Comparator or compareTo(). So if Comparator or compareTo() contradict the equals() method you could find sometimes something unexpected 
  • Emty String is the first String after sorting
Generics
  • Generics doesn't exist in runtime
  • To the List<Object> you can add everything of Object's subclass 
  • You can always pass the generic Collection to the method that take non-generic ones, but you will get compiler warning for it
  • If you will try to add something to the Collection in such method that is not the type of what the Collection is generified, you won't get any exception until you will try to get something from this Collection there you can get ClassCastException. The same exception you will get trying to sort such List.
  • This wildcard <? extends Object> means that the Collection could be parameterized by all subclasses of the Object class and by the Object class itself
  • You couldn't use wildcards in the new instance instantiation (this will give compile error: new ArrayList<? extends Object>())
  • You could use the wildcards in variable declaration: List <? extends Object> list, the same as declaration of method variables
  • You could use wild cards when declaring the returning type of the method
  •  If variable is using: <? extends Object> this means that you won't add (or set) anything to this Collection
  •  If variable is using: <? super Object> you still could add to this Collection
  •  If you are writting <? super Number> it includes all super classer of number (here only Object class), but doesn't include the Number class itself
  • <? extends Object> is absolutely the same as <?>
  • To generify class you can write: class Foo T, and the use T as the generics type
  • You can use wildcards in class creation generics, but you can use question mark, the usage should look like class Foo<X extends Object>
  • If you create class like: class X <X> than the mentioned in the class X will be considered as the generic type
  • It is possible to use few generic types in one class, like: class Foo <X, Y>
  • You can generify the method will look like: <T> void T(){}. So the generic type should go exactly before the method return type
  • During overriding you could override the method that using generic return or input values with concrete classes, but the generic of child class should correctly set up with these concrete classes