Wednesday, August 31, 2016
Tuesday, August 30, 2016
Synchronized is a Java
Synchronized means that the method cannot be executed by two threads at the same time and the JVM take care of enforcing that.
In C++, you will have to use some synchronizationconstruct, like a critical section or a mutex
Another answer from Anders K.
In C++, you will have to use some synchronizationconstruct, like a critical section or a mutex
Another answer from Anders K.
In the (Java) example
public static synchronized Singleton getInstance()
means that only one thread at a time should be able to access the getInstance() method this to avoid a racing condition.
Synchronized Methods from Oracle Java Doc
The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements. The more complex of the two, synchronized statements, are described in the next section. This section is about synchronized methods.
To make a method synchronized, simply add the
synchronized
keyword to its declaration:
public class SynchronizedCounter { private int c = 0;
public synchronized void increment() { c++; }
public synchronized void decrement() { c--; }
public synchronized int value() { return c; }}
public synchronized void increment() { c++; }
public synchronized void decrement() { c--; }
public synchronized int value() { return c; }}
- First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
- Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
If
count
is an instance of SynchronizedCounter
, then making these methods synchronized has two effects:
Note that constructors cannot be synchronized — using the
synchronized
keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.Enumeration in JAVA
Enumeration in JAVA
- Enums are implicitly final subclasses of java.lang.Enum.
- if an enum is a member of a class, it's implicitly static.
- new can never be used with an enum, even within theenum type itself.
- name and valueOf simply use the text of the enum constants, while toString may be overridden to provide any content, if desired.
What are enums and why are they useful?
You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: "permanent", "temp", "apprentice"), or flags ("execute now", "defer execution").
If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
BTW, overuse of enums might mean that your methods do too much (it's often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go.
As an example, which is better?
/** Counts number of foobangs.
* @param type Type of foobangs to count. Can be 1=green foobangs,
* 2=wrinkled foobangs, 3=sweet foobangs, 0=all types.
* @return number of foobangs of type
*/
public int countFoobangs(int type)
versus
/** Types of foobangs. */
public enum FB_TYPE {
GREEN, WRINKLED, SWEET,
/** special type for all types combined */
ALL;
}
/** Counts number of foobangs.
* @param type Type of foobangs to count
* @return number of foobangs of type
*/
public int countFoobangs(FB_TYPE type)
A method call like:
int sweetFoobangCount = countFoobangs(3);
then becomes:
int sweetFoobangCount = countFoobangs(FB_TYPE.SWEET);
In the second example, it's immediately clear which types are allowed, docs and implementation cannot go out of sync, and the compiler can enforce this. Also, an invalid call like
int sweetFoobangCount = countFoobangs(99);
is no longer possible.
Resource Link:
SoftLink:How to create a link to a directory
How to create a link
xxx
to /home/jake/doc/test/2000/something/
?
Assume the
xxx
is created under /home/jake
and you're currently in /home/jake
. When you do cd xxx
, you directly go to /home/jake/doc/test/2000/something/
.
Ans:
Symbolic or soft link (files or directories, more flexible and self documenting)
# Source Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx
Hard link (files only, less flexible and not self documenting)
# Source Link
ln /home/jake/doc/test/2000/something /home/jake/xxx
More information: man ln
Resource Link
Monday, August 29, 2016
PostgreSQL find duplicate records
select TCODE, external_id, count(*)
from TM_EXTERNAL_ACCOUNT
group by TCODE, external_id
HAVING count(*) > 1
from TM_EXTERNAL_ACCOUNT
group by TCODE, external_id
HAVING count(*) > 1
Collections Single Tweak
Q1: What is the difference between ArrayList and Vector ?
Ans:
Vector is synchronized while ArrayList is not . Vector is slow while ArrayList is fast. Every time when needed, Vector increases the capacity twice of its initial size while ArrayList increases its ArraySize by 50%.
Q2 What is the difference between HashMap and Hashtable ?
Ans:
a. HashMap allows one null key and any number of null values while Hashtable does not allow null keys and null values.
b. HashMap is not synchronized or thread-safe while Hashtable is synchronized or thread-safe.
Q3 What is the difference between Iterator and ListIterator.
Ans:
Using Iterator we can traverse the list of objects in forward direction . But ListIterator can traverse the collection in both directions that is forward as well as backward.
Q4 What is the difference between HashSet and TreeSet ?
Ans:
a. HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order
b. HashSet can store null object while TreeSet can not store null object.
Q5 What is the difference between HashMap and ConcurrentHashMap ?Ans:
a. HashMap is not synchronized while ConcurrentHashMap is synchronized.
b. HashMap can have one null key and any number of null values while ConcurrentHashMap does not allow null keys and null values .
Ans:
Vector is synchronized while ArrayList is not . Vector is slow while ArrayList is fast. Every time when needed, Vector increases the capacity twice of its initial size while ArrayList increases its ArraySize by 50%.
Q2 What is the difference between HashMap and Hashtable ?
Ans:
a. HashMap allows one null key and any number of null values while Hashtable does not allow null keys and null values.
b. HashMap is not synchronized or thread-safe while Hashtable is synchronized or thread-safe.
Q3 What is the difference between Iterator and ListIterator.
Ans:
Using Iterator we can traverse the list of objects in forward direction . But ListIterator can traverse the collection in both directions that is forward as well as backward.
Q4 What is the difference between HashSet and TreeSet ?
Ans:
a. HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order
b. HashSet can store null object while TreeSet can not store null object.
Q5 What is the difference between HashMap and ConcurrentHashMap ?Ans:
a. HashMap is not synchronized while ConcurrentHashMap is synchronized.
b. HashMap can have one null key and any number of null values while ConcurrentHashMap does not allow null keys and null values .
Sunday, August 28, 2016
TreeMap how does it sort??
The map is sorted according to the natural ordering of its keys, or by a
Comparator
provided at map creation time, depending on which constructor is used.
It is not only alphabetical, but it is also upper/down case sensitive.
TreeMap<String, Integer> treemap = new TreeMap<String, Integer>();
treemap.put("Lol", 1);
treemap.put("Marc", 2);
treemap.put("Jesper", 3);
treemap.put("lol1", 1);
treemap.put("marc1", 2);
treemap.put("jesper1", 3);
Output:
Jesper = 3
Lol = 1
Marc = 2
jesper1 = 3
lol1 = 1
marc1 = 2
So, if you don't need it, you can use your custom comparator, and compare string in lower case:
TreeMap<String, Integer> treemap = new TreeMap<String, Integer>(new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.toLowerCase().compareTo(o2.toLowerCase());
}
});
treemap.put("Lol", 1);
treemap.put("Marc", 2);
treemap.put("Jesper", 3);
treemap.put("lol1", 1);
treemap.put("marc1", 2);
treemap.put("jesper1", 3);
Output:
Jesper = 3
jesper1 = 3
Lol = 1
lol1 = 1
Marc = 2
marc1 = 2
Resource Link:
http://stackoverflow.com/a/13642719/2293534
Tuesday, August 23, 2016
Liquibase: Database Versioning
- http://bytefilia.com/managing-database-schema-changes-liquibase-existing-schema/
- http://www.liquibase.org/documentation/update.html
- https://github.com/liquibase/liquibase-hibernate/issues/100
- http://www.liquibase.org/documentation/command_line.html
- https://www.youtube.com/watch?v=gwDmXh-PMME
- https://blog.codecentric.de/en/2015/01/managing-database-migrations-using-liquibase/
- http://www.liquibase.org/bestpractices.html
- http://stefanborghys.blogspot.com/2014/02/setting-up-database-using-liquibase-311.html
- http://www.liquibase.org/tutorial-using-oracle
- http://stackoverflow.com/questions/27125521/liquibase-do-not-see-changes-in-entities
- https://github.com/liquibase/liquibase-hibernate/wiki
Download:
Monday, August 22, 2016
Is there a good reason to create really empty abstract class vs interface ?
Hypothetically, you might do this to ensure that there is a single common base class for future anticipated requirements ... or for some other reason.
But generally speaking it is a bad idea ... IMO.
(Of course, things like this often happen for historical reasons; e.g. the
abstract
class may have had more members in the past that have since been removed.)
From Stephen C's Answer
Resource Link: http://stackoverflow.com/a/10123241/2293534
From BalusC Answer:
Resource Link: http://stackoverflow.com/a/10123241/2293534
From BalusC Answer:
The key is that you can extend from only one abstract class, while you can implement moreinterfaces.
Apparently the "empty abstract class" design desicion was made so that it prevents the implementing class from extending from another classes.
If it was me I'd let it go, otherwise it might break. Best is still to contact the original developers and ask for reasoning (and add them as comments in the abstract class for your and future convenience).
Marker Interface
An empty
abstract class
is very much equivalent to an interface
except that it can extend a class
abstract class myAbstractClass // extends anotherClass implements anInterface
{
}
interface myInterface // extends anotherInterface
{
}
This pattern is called Marker interface
Friday, August 19, 2016
bubble sort vs insertion sort
In Bubble sort , at every iteration you find a largest number and push it to bottom (Bubble out larger number)
In Insertion sort you have two regions one sorted and another unsorted.
At Every Iteration you pick up an element from unsorted region and insert at proper location in Sorted region.
Insertion Sort and Bubble sort both have Worst Case O(N^2).
But if the array is mostly sorted Insertion Sort will perform better.
Insertion sort is often used with Quick sort: In Quick Sort after some level of recursion (When array is mostly sorted) Insertion sort is used.
For more:
https://www.quora.com/In-laymans-terms-what-is-the-difference-between-a-bubble-sort-and-an-insert-sort
In Insertion sort you have two regions one sorted and another unsorted.
At Every Iteration you pick up an element from unsorted region and insert at proper location in Sorted region.
Insertion Sort and Bubble sort both have Worst Case O(N^2).
But if the array is mostly sorted Insertion Sort will perform better.
Insertion sort is often used with Quick sort: In Quick Sort after some level of recursion (When array is mostly sorted) Insertion sort is used.
For more:
https://www.quora.com/In-laymans-terms-what-is-the-difference-between-a-bubble-sort-and-an-insert-sort
Thursday, August 18, 2016
How to create immutable class in java?
How to create immutable class in java?
The key points for immutable are:
- no setters methods
- make variables private and final
- return lists using Collections.unmodifiableList - never return any mutable field; always return either a copy (deep if appropriate) or an immutable version of the field
- make class final
- if variables are changed internally in the class this change is not visible and has no effect outside of the class (including affecting things like
equals()
andhashcode()
).
Resource Link:
Tuesday, August 16, 2016
Export specific rows from a PostgreSQL table as INSERT SQL script
This is an easy and fast way to export a table to a script with pgAdmin manually without extra installations:
- Right click on target table and select "Backup".
- Select a file path to store the backup. As Format choose "Plain".
- Open the tab "Dump Options #2" at the bottom and check "Use Column Inserts".
- Click the Backup-button.
- If you open the resulting file with a text reader (e.g. notepad++) you get a script to create the whole table. From there you can simply copy the generated INSERT-Statements.
Step#1:
Step#2:
Step#3:
Step#4:
Resource Link:
Postgresql: could not connect to server: Connection refused (0x0000274D/10061)
Question:
could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" and accepting TCP/IP connections on port 5432?
Do I have to create a windows service? How is it called? Do I have to install it separately?
Answer:
Use services (start -> run -> services.msc) and look for the postgresql-[version] service.
- If it is not there you might have just installed pgAdmin and not installed PostgreSQL itself.
- If it is not running try to start it, if it won't start open the event-viewer (start -> run -> eventvwr) and look for error messages relating to the PostgreSQL service.
- If it does start check the startup type, if you want it to start with windows it should be "Automatic"; or perhaps "Automatic, delayed start" if you don't want it to slow down startup too much.
Adding to the first, because in a different comment you've said the service isn't there. It is possible to download a standalone pgAdmin so you can connect to an external PostgreSQL database. It would seem you have done such a thing, or explicitly chosen to not add the service. Just try theOne Click Installer, which still allows proper configuration of installation directory despite its name.
Resource Link:
Windows Kill Process By Port Number
If you need to kill a process manually on Windows its actually pretty easy. First fire up a command prompt and type the following command.
netstat -a -o -n
To kill the process we need to find the PID of the process in question. I just run down the list by port until I find port 8080 and here you will see the process id was 28344.
Finally with the PID we can run the following command to kill the process
taskkill /F /PID 28344
Specific Port Killing
Open command prompt and run the following commands
C:\Users\username>netstat -o -n -a | findstr 0.0:3000
TCP 0.0.0.0:3000 0.0.0.0:0 LISTENING 3116
C:\Users\username>taskkill /F /PID 3116
, here 3116 is the process ID
Reource Link:
Subscribe to:
Posts (Atom)