Wednesday, December 24, 2014

CSS Animation

A fantastic resource on CSS animation:

http://robots.thoughtbot.com/css-animation-for-beginners

Sunday, November 30, 2014

REST & SOAP

REpresentational State Transfer (REST).

REST provides you with abilities that are similar (such as making a stateless request and receiving an XML response) to typical web services but with less overhead on the server than standard SOAP calls. This means that if you have a heavy load on the server, throughput can be faster. In addition, because REST behaves like a regular web request except that you are returning XML strings, implementing REST can be easier for non-SOAP-experienced developers.

Of course, all of this does have a cost. REST requires clients to do more work in receiving the XML because they have to parse it themselves. In contrast, SOAP has Web Services Description Language (WSDL) and XML Schema Definition (XSD) for strong typing to generate the client code.

My only gripe with RESTful services is that everyone seems to implement them slightly differently. There seems to be a textbook definition of how to use them; the URI has a hierarchy describing what it is you are looking for. The user can then use that hierarchy while sending over different types of requests (for example, GET, DELETE). Those requests will determine what the code does. For example, you could send over /address/123 Main St with the DELETE request, and it would tell the server to delete the address 123 Main St. Then an XML response would be returned. In this example, the response would probably be some sort of confirmation. However, not many RESTful components seem to use this method of calling.

 The request should be a totally stateless request, and the URL you are sending over does not care about what was previously sent or any session. The URL is sent to the server, a request is made, and an XML response is returned. 

Thursday, November 27, 2014

SQL Developer Shotcuts

  1. ctrl-enter : executes the current statement(s)
  2. F5 : executes the current code as a script (think SQL*Plus)
  3. ctrl-space : invokes code insight on demand
  4. ctrl-Up/Dn : replaces worksheet with previous/next SQL from SQL History
  5. ctrl-shift+Up/Dn : same as above but appends instead of replaces
  6. shift+F4 : opens a Describe window for current object at cursor
  7. ctrl+F7 : format SQL
  8. ctrl+/ : toggles line commenting
  9. ctrl+e : incremental search

--

Configuring Keyboard Shortcuts in SQL Developer

Tools > Preferences > Shortcut Keys

Wednesday, November 26, 2014

Making webservice client using command


Before executing the command, we need to go to the Java Home location. IN windows command window, java path can be found by the command path. After that we will have to execute the command as below format:

wsimport  <Service URL in WSDL> -d <destination folder location> -keep


Example of command as : 
wsimport http://10.54.170.81:8080/CoreServices/TxnService?wsdl -d d:\test -keep

This command will make the webservice client at specified location.


Monday, November 24, 2014

Seam’s Integration with the MVC

Most frameworks integrate directly by having you call their framework-specific servlets to
integrate with the architecture. Seam is different; it controls items by adding listeners and
life cycles into the request. This allows us to maintain the normal life cycle of a JSF
request. You saw this already earlier in the chapter when I presented Seam’s basic configuration.
Here I will explain it in a bit more detail.
Before I start explaining how Seam integrates with the various areas, you need to be
aware of a central class: org.jboss.seam.context.Lifecyle. This is the class that will keep
our contexts straight. Contexts will handle state in the web tier in a more advanced way
than a standard request and session object.
As you may recall, in the web.xml a listener (org.jboss.seam.servlet.SeamListener) was
added. You also see this listener being the first thing called in our sequence diagram. This
listener is called only at the start of a new session. This will set ServletContext and Session
to the Lifecycle object for manipulation later.
Now you see the next object called is SeamPhaseListener. The SeamPhaseListener object
is called in connection with FacesServlet. As you saw in faces-config.xml earlier, the
SeamPhaseListener is part of the life cycle for FacesServlet. This again is used to control
much of the context and to store the request state. This listener is needed to help move
the data from the presentation to the business logic tier. In a typical JSF life cycle, you
would use backing beans. Now instead of having to worry about your backing beans
needing to translate the data and call EJBs, Seam will handle this directly for us.


Copied from: Beginnign JBoss Seam by Joseph Faisal Nusairat

Inversion of Control in Seam

Inversion of control, also known by many as dependency injection, takes the need to
instantiate objects away from the normal user calls. Instead, you allow the container to
handle the creation of the component and its subcomponents. Seam is no different in
using dependency injection to inject objects. However, Seam takes it to the next step by
allowing the injection to go both ways.

IoC is needed because of the nature of Seam. Because we don’t use any JSF action
classes to translate our presentation tier requests into objects and then set them on the
EJB and call the EJB, we have to use IoC to make up for it. This helps us save time and
space by letting the container manage the objects.

The usage of IoC in Seam is often referred to as bijection, because the injection is
two-way (injection and “outjection”). You can specify the direction of the components.
However, bijection is so much more in Seam than it is in most typical IoC patterns. Seam
takes IoC and expands it by making it dynamic, contextual, and bidirectional, and allowing
assembly by the container.

So where can you use bijection? Bijection can be used on any object that is a Seam
object. Remember, a Seam object is any object that you have defined with an @Name annotation
on the class. You can then biject your Seam objects into any SB or JavaBean.
However, you cannot biject objects into your EB. This is because the domain model
should be independent of business logic and because EBs are instantiated at the application
level and Seam could not intercept them anyway.

Seam performs bijection by dividing it into two areas: one going into the system and
one going out. As I have said, these are more commonly defined as injection and outjection,
and we use @In and @Out for these, respectively.

Monday, September 1, 2014

Programming Quotes

This post serves as a compilation of great programming quotes, quotes from famous programmers, computer scientists and savvy entrepreneurs of our time. Some of them are funny, some of them are motivational, some of them are… just awesome!
So, in no particular order, let’s see what we have…
1. “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”
C.A.R. Hoare (British computer scientist, winner of the 1980 Turing Award)
2. “If debugging is the process of removing software bugs, then programming must be the process of putting them in.”
Edsger Dijkstra (Dutch computer scientist, winner of the 1972 Turing Award)
3. “Measuring programming progress by lines of code is like measuring aircraft building progress by weight.”
Bill Gates (co-founder of Microsoft)
4. “Nine people can’t make a baby in a month.” (regarding the addition of more programmers to get a project completed faster)
Fred Brooks (American computer scientist, winner of the 1999 Turing Award)
5. “Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”
Brian W. Kernighan (Canadian computer scientist, co-author of “C programming language”)
6. “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”
- Martin Golding
7. “C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do, it blows away your whole leg.”
Bjarne Stroustrup (Danish computer scientist, developer of the C++ programming language)
8. “When debugging, novices insert corrective code; experts remove defective code.”
- Richard Pattis
9. “Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter.”
Eric S. Raymond (American programmer, open source software advocate, author of “The Cathedral and the Bazaar”)
10. “Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.”
Linus Torvalds (Finnish American, software engineer and hacker, principal force behind the development of the Linux kernel)
11. “Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.”
- Rich Cook
12. “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
Martin Fowler (author and speaker on software development)
13. “Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’”
Steve McConnell (author of many software engineering books including “Code Complete”)
14. “The problem with using C++ … is that there’s already a strong tendency in the language to require you to know everything before you can do anything.”
Larry Wall (developer of the Perl language)
15. “People think that computer science is the art of geniuses but the actual reality is the opposite, just many people doing things that build on each other, like a wall of mini stones.”
Donald Knuth (computer scientist)
16. “One of my most productive days was throwing away 1000 lines of code.”
Ken Thompson (computer scientist, early developer of UNIX OS)
17. “Most software today is very much like an Egyptian pyramid with millions of bricks piled on top of each other, with no structural integrity, but just done by brute force and thousands of slaves.”
Alan Kay (American computer scientist)
18. “Before software can be reusable it first has to be usable.”
- Ralph Johnson (computer scientist)
19. “Programming is like sex. One mistake and you have to support it for the rest of your life.”
- Michael Sinz
20) “If builders built buildings the way programmers wrote programs, then the first woodpecker that came along wound destroy civilization.”
Gerald Weinberg (American computer scientist)

Interview questions from Java Multi-threading and Concurrency

Here is our list of top questions from Java thread, concurrency and multi-threading. You can use this list to prepare well for your Java interview.

  1. What is Thread in Java?
  2. Thread is an independent path of execution. It’s way to take advantage of multiple CPU available in a machine. By employing multiple threads you can speed up CPU bound task. For example, if one thread takes 100 millisecond to do a job, you can use 10 thread to reduce that task into 10 millisecond. Java provides excellent support for multi-threading at language level, and its also one of strong selling point. For more details see here.

  3. Difference between Thread and Process in Java?
  4. Thread is subset of Process, in other words one process can contain multiple threads. Two process runs on different memory space, but all threads share same memory space. Don’t confuse this with stack memory, which is different for different thread and used to store local data to that thread. For more detail see this answer.

  5. How do you implement Thread in Java?
  6. At language level, there are two ways to implement Thread in Java. An instance of java.lang.Thread represent a thread but it need a task to execute, which is instance of interface java.lang.Runnable. Since Thread class itself implement Runnable, you can override run() method either by extending Thread class or just implementing Runnable interface. For detailed answer and discussion see this article.

  7. When to use Runnable vs Thread in Java?
  8. This is follow-up of previous multi-threading interview question. As we know we can implement thread either by extending Thread class or implementing Runnable interface, question arise, which one is better and when to use one? This question will be easy to answer, if you know that Java programming language doesn’t support multiple inheritance of class, but it allows you to implement multiple interface. Which means, its better to implement Runnable than extends Thread, if you also want to extend another class e.g. Canvas or CommandListener. For more points and discussion you can also refer this post.

  9. Difference between start() and run() method of Thread class? 
  10. One of trick Java question from early days, but still good enough to differentiate between shallow understanding of Java threading model start() method is used to start newly created thread, while start() internally calls run() method, there is difference calling run() method directly. When you invoke run() as normal method, its called in the same thread, no new thread is started, which is the case when you call start() method. Read this answer for much more detailed discussion.

  11. Difference between Runnable and Callable in Java?
  12. Both Runnable and Callable represent task which is intended to be executed in separate thread. Runnable is there from JDK 1.0, while Callable was added on JDK 1.5. Main difference between these two is that Callable’s call() method can return value and throw Exception, which was not possible with Runnable’s run() method. Callable return Future object, which can hold result of computation. See my blog post on same topic for more in-depth answer of this question.

  13. Difference between CyclicBarrier and CountDownLatch in Java? 
  14. Though both CyclicBarrier and CountDownLatch wait for number of threads on one or more events, main difference between them is that you can not re-use CountDownLatch once count reaches to zero, but you can reuse same CyclicBarrier even after barrier is broken.  See this answer for few more points and sample code example.

  15. What is Java Memory model?
  16. Java Memory model is set of rules and guidelines which allows Java programs to behave deterministically across multiple memory architecture, CPU, and operating system. It’s particularly important in case of multi-threading. Java Memory Model provides some guarantee on which changes made by one thread should be visible to others, one of them is happens-before relationship. This relationship defines several rules which allows programmers to anticipate and reason behaviour of concurrent Java programs. For example, happens-before relationship guarantees :
    • Each action in a thread happens-before every action in that thread that comes later in the program order, this is known as program order rule.
    • An unlock on a monitor lock happens-before every subsequent lock on that same monitor lock, also known as Monitor lock rule.
    • A write to a volatile field happens-before every subsequent read of that same field, known as Volatile variable rule.
    • A call to Thread.start on a thread happens-before any other thread detects that thread has terminated, either by successfully return from Thread.join() or by Thread.isAlive() returning false, also known as Thread start rule.
    • A thread calling interrupt on another thread happens-before the interrupted thread detects the interrupt( either by having InterruptedException thrown, or invoking isInterrupted or interrupted), popularly known as Thread Interruption rule.
    • The end of a constructor for an object happens-before the start of the finalizer for that object, known as Finalizer rule.
    • If A happens-before B, and B happens-before C, then A happens-before C, which means happens-before guarantees Transitivity.
    I strongly suggest to read Chapter 16 of Java Concurrency in Practice to understand Java Memory model in more detail.

  17. What is volatile variable in Java?
  18. volatile is a special modifier, which can only be used with instance variables. In concurrent Java programs, changes made by multiple threads on instance variables is not visible to other in absence of any synchronizers e.g. synchronized keyword or locks. Volatile variable guarantees that a write will happen before any subsequent read, as stated “volatile variable rule” in previous question. Read this answer to learn more about volatile variable and when to use them.

  19. What is thread-safety? is Vector a thread-safe class?
  20. (Yes, see details)
    Thread-safety is a property of an object or code which guarantees that if executed or used by multiple thread in any manner e.g. read vs write it will behave as expected. For example, a thread-safe counter object will not miss any count if same instance of that counter is shared among multiple threads. Apparently, you can also divide collection classes in two category, thread-safe and non-thread-safe. Vector is indeed a thread-safe class and it achieves thread-safety by synchronizing methods which modifies state of Vector, on the other hand, its counterpart ArrayList is not thread-safe.

  21. What is race condition in Java? Given one example? 
  22. Race condition are cause of some subtle programming bugs when Java programs are exposed to concurrent execution environment. As name suggests, race condition occurs due to race between multiple threads, if a thread which is supposed to execute first lost the race and executed second, behaviour of code changes, which surface as non-deterministic bugs. This is one of the hardest bugs to find and re-produce because of random nature of racing between threads. One example of race condition is out-of-order processing, see this answer for some more example of race conditions in Java programs.

  23. How to stop thread in Java?
  24. I always said that Java provides rich APIs for everything but ironically Java doesn’t provide a sure shot way of stopping thread. There was some control methods in JDK 1.0 e.g. stop(), suspend() and resume() which was deprecated in later releases due to potential deadlock threats, from then Java API designers has not made any effort to provide a consistent, thread-safe and elegant way to stop threads. Programmers mainly rely on the fact that thread stops automatically as soon as they finish execution of run() or call() method. To manually stop, programmers either take advantage of volatile boolean variable and check in every iteration if run method has loops or interrupt threads to abruptly cancel tasks. See this tutorial for sample code of stopping thread in Java.

  25. What happens when an Exception occurs in a thread?
  26. This is one of the good tricky Java question I have seen on interviews. In simple words, If not caught thread will die, if an uncaught exception handler is registered then it will get a call back. Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler’s uncaughtException() method, passing the thread and the exception as arguments.

  27. How do you share data between two thread in Java?
  28. You can share data between threads by using shared object, or concurrent data-structure like BlockingQueue. See this tutorial to learn inter thread communication in Java. It implements Producer consumer pattern using wait and notify methods, which involves sharing objects between two threads.

  29. Difference between notify and notifyAll in Java?
  30. This is another tricky questions from core Java interviews, since multiple threads can wait on single monitor lock, Java API designer provides method to inform only one of them or all of them, once waiting condition changes, but they provide half implementation. There notify() method doesn’t provide any way to choose a particular thread, that’s why its only useful when you know that there is only one thread is waiting. On the other hand, notifyAll() sends notification to all threads and allows them to compete for locks, which ensures that at-least one thread will proceed further. See my blog post on similar topic for more detailed answer and code example.

  31. Why wait, notify and notifyAll are not inside thread class? 
  32. This is a design related question, which checks what candidate thinks about existing system or does he ever thought of something which is so common but looks in-appropriate at first. In order to answer this question, you have to give some reasons why it make sense for these three method to be in Object class, and why not on Thread class. One reason which is obvious is that Java provides lock at object level not at thread level. Every object has lock, which is acquired by thread. Now if thread needs to wait for certain lock it make sense to call wait() on that object rather than on that thread. Had wait() method declared on Thread class, it was not clear that for which lock thread was waiting. In short, since wait, notify and notifyAll operate at lock level, it make sense to defined it on object class because lock belongs to object. You can also see this article for more elaborate answer of this question.

  33. What is ThreadLocal variable in Java? 
  34. ThreadLocal variables are special kind of variable available to Java programmer. Just like instance variable is per instance, ThreadLocal variable is per thread. It’s a nice way to achieve thread-safety of expensive-to-create objects, for example you can make SimpleDateFormat thread-safe using ThreadLocal. Since that class is expensive, its not good to use it in local scope, which requires separate instance on each invocation. By providing each thread their own copy, you shoot two birds in one arrow. First, you reduce number of instance of expensive object by reusing fixed number of instances, and Second, you achieve thread-safety without paying cost of synchronization or immutability. Another good example of thread local variable is ThreadLocalRandom class, which reduces number of instances of expensive-to-create Random object in multi-threading environment. See this answer to learn more about thread local variables in Java.

  35. What is FutureTask in Java?
  36. FutureTask represents a cancellable asynchronous computation in concurrent Java application. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. A FutureTask object can be used to wrap a Callable or Runnable object. Since FutureTask
    also implements Runnable, it can be submitted to an Executor for execution.

  37. Difference between interrupted and isInterrupted method in Java?
  38. Main difference between interrupted() and isInterrupted() is that former clears the interrupt status while later does not. The interrupt mechanism in Java multi-threading is implemented using an internal flag known as the interrupt status. Interrupting a thread by calling Thread.interrupt() sets this flag. When interrupted thread checks for an interrupt by invoking the static methodThread.interrupted(), interrupt status is cleared. The non-static isInterrupted() method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag. By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it’s always possible that interrupt status will immediately be set again, by another thread invoking interrupt.

  39. Why wait and notify method are called from synchronized block?
  40. Main reason for calling wait and notify method from either synchronized block or method is that it made mandatory by Java API. If you don’t call them from synchronized context, your code will throw IllegalMonitorStateException. A more subtle reason is to avoid race condition between wait and notify calls. To learn more about this, check my similarly titled post here.

  41. Why you should check condition for waiting in a loop?
  42. Its possible for a waiting thread to receive false alerts and spurious wake up calls, if it doesn’t check the waiting condition in loop, it will simply exit even if condition is not met. As such, when a waiting thread wakes up, it cannot assume that the state it was waiting for is still valid. It may have been valid in the past, but the state may have been changed after the notify() method was called and before the waiting thread woke up. That’s why it always better to call wait() method from loop, you can even create template for calling wait and notify in Eclipse. To learn more about this question, I would recommend you to read Effective Java items on thread and synchronization.

  43. Difference between synchronized and concurrent collection in Java?
  44. Though both synchronized and concurrent collection provides thread-safe collection suitable for multi-threaded and concurrent access, later is more scalable than former. Before Java 1.5, Java programmers only had synchronized collection which becomes source of contention if multiple thread access them concurrently, which hampers scalability of system. Java 5 introduced concurrent collections like ConcurrentHashMap, which not only provides thread-safety but also improves scalability by using modern techniques like lock stripping and partitioning internal table. See this answer for more differences between synchronized and concurrent collection in Java.

  45. Difference between Stack and Heap in Java?
  46. Why do someone this question as part of multi-threading and concurrency? because Stack is a memory area which is closely associated with threads. To answer this question, both stack and heap are specific memories in Java application. Each thread has their own stack, which is used to store local variables, method parameters and call stack. Variable stored in one Thread’s stack is not visible to other. On other hand, heap is a common memory area which is shared by all threads. Objects whether local or at any level is created inside heap. To improve performance thread tends to cache values from heap into their stack, which can create problems if that variable is modified by more than one thread, this is where volatile variables comes in picture. volatile suggest threads to read value of variable always from main memory. See this article to learn more about stack and heap in Java to answer this question in greater detail.

  47. What is thread pool? Why should you thread pool in Java? 
  48. Creating thread is expensive in terms of time and resource. If you create thread at time of request processing it will slow down your response time, also there is only a limited number of threads a process can create. To avoid both of these issue, a pool of thread is created when application starts-up and threads are reused for request processing. This pool of thread is known as “thread pool” and threads are known as worker thread. From JDK 1.5 release, Java API provides Executor framework, which allows you to create different types of thread pools e.g. single thread pool, which process one task at a time, fixed thread pool (a pool of fixed number of thread) or cached thread pool (an expandable thread pool suitable for applications with many short lived tasks). See thisarticle to learn more about thread pools in Java to prepare detailed answer of this question.

  49. Write code to solve Producer Consumer problem in Java?
  50. Most of the threading problem you solved in real world are of category of Producer consumer pattern, where one thread is producing task and other thread is consuming that. You must know how to do inter thread communication to solve this problem. At lowest level, you can use wait and notify to solve this problem, and at high level you can leverage Semaphore or BlockingQueue to implement Producer consumer pattern, as shown in this tutorial.

  51. How do you avoid deadlock in Java? Write Code?
  52. deadlock in Java
    Deadlock is a condition in which two threads wait for each other to take action which allows them to move further. It’s a serious issue because when it happen your program hangs and doesn’t do the task it is intended for. In order for deadlock to happen, following four condition must be true :
    • Mutual Exclusion : At least one resource must be held in a non-shareable mode. Only one process can use the resource at any given instant of time.
    • Hold and Wait : A process is currently holding at least one resource and requesting additional resources which are being held by other processes.
    • No Pre-emption : The operating system must not de-allocate resources once they have been allocated; they must be released by the holding process voluntarily.
    • Circular Wait : A process must be waiting for a resource which is being held by another process, which in turn is waiting for the first process to release the resource.
    Easiest way to avoid deadlock is to prevent Circular wait, and this can be done by acquiring locks in a particular order and releasing them in reverse order, so that a thread can only proceed to acquire a lock if it held the other one. Check this tutorial for actual code example and detailed discussion on techniques of avoiding deadlock in Java.

  53. Difference between livelock and deadlock in Java?
  54. This question is extension of previous interview question. A livelock is similar to a deadlock, except that the states of the threads or processes involved in the livelock constantly change with regard to one another, without any one progressing further. Livelock is a special case of resource starvation. A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time. In short, main difference between livelock and deadlock is that in former state of process change but no progress is made.

  55. How do you check if a Thread holds a lock or not?
  56. I didn’t even know that you can check if a Thread already holds lock before this question hits me in a telephonic round of Java interview. There is a method called holdsLock() on java.lang.Thread, it returns true if and only if the current thread holds the monitor lock on the specified object. You can also check this article for more detailed answer.

  57. How do you take thread dump in Java?
  58. There are multiple ways to take thread dump of Java process depending upon operating system. When you take thread dump, JVM dumps state of all threads in log files or standard error console. In windows you can use Ctrl + Break key combination to take thread dump, on Linux you can use kill -3 command for same. You can also use a tool called jstack for taking thread dump, it operate on process id, which can be found using another tool called jps.

  59. Which JVM parameter is used to control stack size of thread?
  60. This is the simple one, -Xss parameter is used to control stack size of Thread in Java. You can see this list of JVM options to learn more about this parameter.

  61. Difference between synchronized and ReentrantLock in Java?
  62. There were days when only way to provide mutual exclusion in Java was via synchronized keyword, but it has several shortcomings e.g. you can not extend lock beyond a method or block boundary, you can not give up trying for a lock etc. Java 5 solves this problem by providing more sophisticated control via Lock interface. ReentrantLock is a common implementation of Lock interface and provides re-entrant mutual exclusion Lock with the same basic behaviour and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities. See this article to learn about those capabilities and some more differences between synchronized vs ReentrantLock in Java.

  63. There are three threads T1, T2 and T3? How do you ensure sequence T1, T2, T3 in Java?
  64. Sequencing in multi-threading can be achieved by different means but you can simply use join() method of thread class to start a thread when another one is finished its execution. To ensure three threads execute you need to start the last one first e.g. T3 and then call join methods in reverse order e.g. T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. To learn more about join method, see this tutorial.

  65. What does yield method of Thread class do?
  66. Yield method is one way to request current thread to relinquish CPU so that other thread can get chance to execute. Yield is a static method and only guarantees that current thread will relinquish the CPU but doesn’t say anything about which other thread will get CPU. Its possible for same thread to get CPU back and start its execution again. See this article to learn more about yield method and to answer this question better.

  67. What is concurrence level of ConcurrentHashMap in Java?
  68. ConcurrentHashMap achieves it’s scalability and thread-safety by partitioning actual map into number of sections. This partitioning is achieved using concurrency level. It’s optional parameter of ConcurrentHashMap constructor and it’s default value is 16. The table is internally partitioned to try to permit the indicated number of concurrent updates without contention. To learn more about concurrency level and internal resizing, see my post How ConcurrentHashMap works in Java.

  69. What is Semaphore in Java?
  70. Semaphore in Java is a new kind of synchronizer. It’s a counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly. Semaphore is used to protect expensive resource which is available in fixed number e.g. database connection in pool. See this article to learn more about counting Semaphore in Java.

  71. What happens if you submit task, when queue of thread pool is already fill?
  72. This is another tricky question in my list. Many programmer will think that it will block until a task is cleared but its true. ThreadPoolExecutor’s submit() method throws RejectedExecutionException if the task cannot be scheduled for execution.

  73. Difference between submit() and execute() method thread pool in Java?
  74. Both method are ways to submit task to thread pools but there is slight difference between them. execute(Runnable command) is defined in Executor interface and executes given task in future, but more importantly it does not return anything. It’s return type is void. On other hand submit() is overloaded method, it can take either Runnable or Callable task and can return Future object which can hold pending result of computation. This method is defined on ExecutorService interface, which extends Executor interface, and every other thread pool class e.g. ThreadPoolExecutor or ScheduledThreadPoolExecutor gets these methods. To learn more about thread pools you can check this article.

  75. What is blocking method in Java?
  76. A blocking method is a method which blocks until task is done, for example accept() method of ServerSocket blocks until a client is connected. here blocking means control will not return to caller until task is finished. On the other hand there are asynchronous or non-blocking method which returns even before task is finished. To learn more about blocking method see this answer.

  77. Is Swing thread-safe? What do you mean by Swing thread-safe?
  78. You can simply this question as No, Swing is not thread-safe, but you have to explain what you mean by that even if interviewer doesn’t ask about it. When we say swing is not thread-safe we usually refer its component, which can not be modified in multiple threads. All update to GUI components has to be done on AWT thread, and Swing provides synchronous and asynchronous callback methods to schedule such updates. You can also read my article to learn more about swing and thread-safety to better answer this question. Even next two questions are also related to this concept.

  79. Difference between invokeAndWait and invokeLater in Java?
  80. These are two methods Swing API provides Java developers to update GUI components from threads other than Event dispatcher thread. InvokeAndWait() synchronously update GUI component, for example a progress bar, once progress is made, bar should also be updated to reflect that change. If progress is tracked in a different thread, it has to call invokeAndWait() to schedule an update of that component by Event dispatcher thread. On other hand, invokeLater() is asynchronous call to update components. You can also refer this answer for more points.

  81. Which method of Swing API are thread-safe in Java?
  82. This question is again related to swing and thread-safety, though components are not thread-safe there are certain method which can be safely call from multiple threads. I know about repaint(), and revalidate() being thread-safe but there are other methods on different swing components e.g. setText() method of JTextComponent, insert() and append() method of JTextArea class.

  83. How to create Immutable object in Java?
  84. This question might not look related to multi-threading and concurrency, but it is. Immutability helps to simplify already complex concurrent code in Java. Since immutable object can be shared without any synchronization its very dear to Java developers. Core value object, which is meant to be shared among thread should be immutable for performance and simplicity. Unfortunately there is no @Immutable annotation in Java, which can make your object immutable, hard work must be done by Java developers. You need to keep basics like initializing state in constructor, no setter methods, no leaking of reference, keeping separate copy of mutable object to create Immutable object. For step by step guide see my post, how to make an object Immutable in Java. This will give you enough material to answer this question with confidence.

  85. What is ReadWriteLock in Java?
  86. In general, read write lock is result of lock stripping technique to improve performance of concurrent applications. In Java, ReadWriteLock is an interface which was added in Java 5 release. A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive. If you want you can implement this interface with your own set of rules, otherwise you can use ReentrantReadWriteLock, which comes along with JDK and supports a maximum of 65535 recursive write locks and 65535 read locks.

  87. What is busy spin in multi-threading?
  88. Busy spin is a technique which concurrent programmers employ to make a thread wait on certain condition. Unlike traditional methods e.g. wait(), sleep() or yield() which all involves relinquishing CPU control, this method does not relinquish CPU, instead it just runs empty loop. Why would someone do that? to preserve CPU caches. In multi core system, its possible for a paused thread to resume on different core, which means rebuilding cache again. To avoid cost of rebuilding cache, programmer prefer to wait for much smaller time doing busy spin. You can also see this answer to learn more about this question.

  89. Difference between volatile and atomic variable in Java?
  90. This is an interesting question for Java programmer, at first, volatile and atomic variable look very similar, but they are different. Volatile variable provides you happens-before guarantee that a write will happen before any subsequent write, it doesn’t guarantee atomicity. For example count++ operation will not become atomic just by declaring count variable as volatile. On the other hand AtomicInteger class provides atomic method to perform such compound operation atomically e.g. getAndIncrement() is atomic replacement of increment operator. It can be used to atomically increment current value by one. Similarly you have atomic version for other data type and reference variable as well.

  91. What happens if a thread throws an Exception inside synchronized block?
  92. This is one more tricky question for average Java programmer, if he can bring the fact about whether lock is released or not is key indicator of his understanding. To answer this question, no matter how you exist synchronized block, either normally by finishing execution or abruptly by throwing exception, thread releases the lock it acquired while entering that synchronized block. This is actually one of the reason I like synchronized block over lock interface, which requires explicit attention to release lock, generally this is achieved by releasing lock in finally block.

  93. What is double checked locking of Singleton?
  94. This is one of the very popular question on Java interviews, and despite its popularity, chances of candidate answering this question satisfactory is only 50%. Half of the time, they failed to write code for double checked locking and half of the time they failed how it was broken and fixed on Java 1.5. This is actually an old way of creating thread-safe singleton, which tries to optimize performance by only locking when Singleton instance is created first time, but because of complexity and the fact it was broken for JDK 1.4,  I personally don’t like it. Anyway, even if you not prefer this approach its good to know from interview point of view. Since this question deserve a detailed answer, I have answered in a separate post, you can read my post how double checked locking on Singleton works to learn more about it.

  95. How to create thread-safe Singleton in Java?
  96. This question is actually follow-up of previous question. If you say you don’t like double checked locking then Interviewer is bound to ask about alternative ways of creating thread-safe Singleton class. There are actually man, you can take advantage of class loading and static variable initialization feature of JVM to create instance of Singleton, or you can leverage powerful enumeration type in Java to create Singleton. I actually preferred that way, you can also read this article to learn more about it and see some sample code.

  97. List down 3 multi-threading best practice you follow?
  98. This is my favourite question, because I believe that you must follow certain best practices while writing concurrent code which helps in performance, debugging and maintenance. Following are three best practices, I think an average Java programmer should follow:
    • Always give meaningful name to your threadThis goes a long way to find a bug or trace an execution in concurrent code. OrderProcessor, QuoteProcessor or TradeProcessor is much better than Thread-1. Thread-2 and Thread-3. Name should say about task done by that thread. All major framework and even JDK follow this best practice.
    • Avoid locking or Reduce scope of Synchronization
      Locking is costly and context switching is even more costlier. Try to avoid synchronization and locking as much as possible and at bare minimum, you should reduce critical section. That’s why I prefer synchronized block over synchronized method, because it gives you absolute control on scope of locking.
    • Prefer Synchronizers over wait and notify
      Synchronizers like CountDownLatch, Semaphore, CyclicBarrier or Exchanger simplifies coding. It’s very difficult to implement complex control flow right using wait and notify. Secondly, these classes are written and maintained by best in business and there is good chance that they are optimized or replaced by better performance code in subsequent JDK releases. By using higher level synchronization utilities, you automatically get all these benefits.
    • Prefer Concurrent Collection over Synchronized Collection
      This is another simple best practice which is easy to follow but reap good benefits. Concurrent collection are more scalable than their synchronized counterpart, that’s why its better to use them while writing concurrent code. So next time if you need map, think about ConcurrentHashMap before thinking Hashtable. See my article Concurrent Collections in Java, to learn more about modern collection classes and how to make best use of them.

  99. How do you force start a Thread in Java?
  100. This question is like how do you force garbage collection in Java, their is no way, though you can make request using System.gc() but its not guaranteed. On Java multi-threading their is absolute no way to force start a thread, this is controlled by thread scheduler and Java exposes no API to control thread schedule. This is still a random bit in Java.

  101. What is fork join framework in Java?
  102. The fork join framework, introduced in JDK 7 is a powerful tool available to Java developer to take advantage of multiple processors of modern day servers. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application. One significant advantage of The fork/join framework is that it uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy. See this article for much more detailed answer of this question.

  103. What is difference between calling wait() and sleep() method in Java multi-threading?
  104. Though both wait and sleep introduce some form of pause in Java application, they are tool for different needs. Wait method is used for inter thread communication, it relinquish lock if waiting condition is true and wait for notification when due to action of another thread waiting condition becomes false. On the other hand sleep() method is just to relinquish CPU or stop execution of current thread for specified time duration. Calling sleep method doesn’t release the lock held by current thread. You can also take look at this article to answer this question with more details.

Thursday, August 21, 2014

Layout in Java Desktop Application

In general, layout managers are objects used in widget toolkits that have the ability to arrange widgets by their relative positions. Java uses layout managers to arrange components in a consistent manner across all windowing platforms.
In this section, we will introduce the following Swing layout managers:
Layout ManagerDescription
FlowLayoutObjects that arrange components in a directional flow, much like lines of text in a paragraph.
GridLayoutObjects that divide the container into equal-sized rectangles and arrange each component into one of these cells.
BorderLayoutObjects that arrange components to the top, bottom, left, right, and center of a container.
To demonstrate these layout managers, we will create an Applet that allows the user to select a layout manager from a list and see the effects it has on some Swing components. In this implementation, we use a BorderLayout manager to place a drop-down list above a panel that contains serveral Swing components (buttons). When an item in the drop-down list is selected, the layout manager for the panel is changed, and without explicitly setting the bounds of any components, the layout manager rearranges the buttons.

Tuesday, June 24, 2014

To check the existence of session before doing any operation in Struts 2 application, we can use interceptor. For implementation of this, we will have to follow some easy steps:

Step 1: Make an interceptor class as below:

public class LoginInterceptor extends AbstractInterceptor {
      @Override
       public String intercept(final ActionInvocation invocation) throws Exception {
        Map session = ActionContext.getContext().getSession();

        UserVo userVo = (UserVo) session.get(Constant.LOGGEDIN_USER_KEY);
        String userLoggedin="";
        if(userVo!=null){
            userLoggedin = userVo.getUsername();

        }
        Object action = invocation.getAction();
        // user is not logged in yet
        if(userLoggedin == null||userLoggedin.equals("")){      

            // Pages that require the user to be logged in - user not logged in yet
            if (!(action instanceof BaseAction)) {
                 return "loginRedirect";
            }      
        }
        // user is logged in
        else{
             return invocation.invoke();
        }
        return invocation.invoke();
    }
}


Step 2: In struts.xml configuration file, add in the package of

 
<interceptors> <interceptor name='login' class='com.dbbl.mbs.portal.auth.LoginInterceptor'> 
 </interceptor> <interceptor-stack name='loginStack'> 
 <interceptor-ref name='login'>
</interceptor-ref> 
<interceptor-ref name='defaultStack'>
</interceptor-ref> 
</interceptor-stack> 
</interceptors> 
<default-interceptor-ref name=&quot;loginStack&quot; /> 
 <global-results> 
<result name=&quot;loginRedirect&quot; type=&quot;redirect&quot;>/login.jsp</result> 
</global-results>


That's the start of the epic.

Sunday, June 22, 2014

To get conditional Sum in BI reporting

In some cases, we need to get the sum of values of a column depending on the values of other column in BI reporting.

For that case, we can do that in a simple way of one line of code as:

<? sum(current-group()/LCY_BAL[../IS_LEAF='Y']) ?> 

In the above code we have get the sum of LCY_BAL field group wise. And the condition for this sum has been implemented in [../IS_LEAF='Y'] . This condition will filter the sum according to the case it supports.


Sunday, May 18, 2014

Seam

At the heart of Seam is the contextual component model.
(1) Seam is a factory that constructs objects according to component definitions.
(2) After creation, each object is stored in the container under one of several contexts (i.e. variable scopes) with varying lifetimes, making the objects contextual and capable of holding state (i.e.stateful).
(3) Seam promotes the interaction of these stateful objects across contexts, assembling them together

Monday, March 24, 2014

Python

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Sunday, February 16, 2014

Differences between Interface and Abstract Class

  1. Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
  2. Variables declared in a Java interface is by default final. An  abstract class may contain non-final variables.
  3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
  4. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
  5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
  6. A Java class can implement multiple interfaces but it can extend only one abstract class.
  7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
  8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

Monday, February 3, 2014

jasperviewer closes main application

at the time of closing jasperviewer report that is opened up, main application window is closed at the same time.To get rid form this problem:

in the constructor of JasperViewer there is boolean indicating whehter it should perform an exit on close.

jasperReport = JasperCompileManager.compileReport( "reportloh.jrxml");
jasperPrint = JasperFillManager.fillReport( jasperReport, parameters, conn);
JasperViewer jv = new JasperViewer( jasperPrint, false );
jv.viewReport( jasperPrint, false );
 

Wednesday, January 15, 2014

To add a new user to a MySQL database from the Linux command line

This method should work from any operating system that uses the MySQL client application from a terminal.
First we need to log into MySQL on a server so lets do that right now.

 
mysql -u root -p
Then enter your password and hit enter. Now we want to create a database which our new user will have privileges on. If you already have a database you can skip this step.


mysql > create database new_database;
 
Now with our new database in place called new_database we can move on and set up a user for this schema.


mysql > grant usage on *.* to new_database_user@localhost identified by user_password';
 
Now we want the new user to be able to do almost everything in the new database so we run:

mysql > grant all privileges on new_database.* to new_database_user@localhost;
Now to make sure all the settings we entered stick we run:


mysql > flush privileges;
 
Now you should be able to easily log in to the database called new_database on the localhost. If you wanted the user to be able to access the database from any location than you would run the following line instead of the one above:


mysql > grant usage on *.* to new_database_user@'%' identified by 'user_password';
 
Hope this helps people remember how to add users really is in MySQL on the command line.