1 . Examples of GoF Design Patterns in Java's core libraries?

Answer :

Creational patterns

Abstract factory (recognizeable by creational methods returning the factory itself which in turn can be used to create another abstract/interface type)

  • javax.xml.parsers.DocumentBuilderFactory#newInstance()
  • javax.xml.transform.TransformerFactory#newInstance()
  • javax.xml.xpath.XPathFactory#newInstance()

Builder (recognizeable by creational methods returning the instance itself)

  • java.lang.StringBuilder#append() (unsynchronized)
  • java.lang.StringBuffer#append() (synchronized)
  • java.nio.ByteBuffer#put() (also on CharBufferShortBufferIntBufferLongBufferFloatBuffer and DoubleBuffer)
  • javax.swing.GroupLayout.Group#addComponent()
  • All implementations of java.lang.Appendable
  • java.util.stream.Stream.Builder

Factory method (recognizeable by creational methods returning an implementation of an abstract/interface type)

  • java.util.Calendar#getInstance()
  • java.util.ResourceBundle#getBundle()
  • java.text.NumberFormat#getInstance()
  • java.nio.charset.Charset#forName()
  • java.net.URLStreamHandlerFactory#createURLStreamHandler(String) (Returns singleton object per protocol)
  • java.util.EnumSet#of()
  • javax.xml.bind.JAXBContext#createMarshaller() and other similar methods

Prototype (recognizeable by creational methods returning a different instance of itself with the same properties)

  • java.lang.Object#clone() (the class has to implement java.lang.Cloneable)

Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)

  • java.lang.Runtime#getRuntime()
  • java.awt.Desktop#getDesktop()
  • java.lang.System#getSecurityManager()

Structural patterns

Adapter (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own/another abstract/interface type which decorates/overrides the given instance)

  • java.util.Arrays#asList()
  • java.util.Collections#list()
  • java.util.Collections#enumeration()
  • java.io.InputStreamReader(InputStream) (returns a Reader)
  • java.io.OutputStreamWriter(OutputStream) (returns a Writer)
  • javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal()

Bridge (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own abstract/interface type which delegates/uses the given instance)

  • None comes to mind yet. A fictive example would be new LinkedHashMap(LinkedHashSet<K>, List<V>) which returns an unmodifiable linked map which doesn't clone the items, but usesthem. The java.util.Collections#newSetFromMap() and singletonXXX() methods however comes close.

Composite (recognizeable by behavioral methods taking an instance of same abstract/interface type into a tree structure)

  • java.awt.Container#add(Component) (practically all over Swing thus)
  • javax.faces.component.UIComponent#getChildren() (practically all over JSF UI thus)

Decorator (recognizeable by creational methods taking an instance of same abstract/interface type which adds additional behaviour)

  • All subclasses of java.io.InputStreamOutputStreamReader and Writer have a constructor taking an instance of same type.
  • java.util.Collections, the checkedXXX()synchronizedXXX() and unmodifiableXXX()methods.
  • javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper
  • javax.swing.JScrollPane

Facade (recognizeable by behavioral methods which internally uses instances of different independent abstract/interface types)

  • javax.faces.context.FacesContext, it internally uses among others the abstract/interface types LifeCycleViewHandlerNavigationHandler and many more without that the enduser has to worry about it (which are however overrideable by injection).
  • javax.faces.context.ExternalContext, which internally uses ServletContextHttpSessionHttpServletRequestHttpServletResponse, etc.

Flyweight (recognizeable by creational methods returning a cached instance, a bit the "multiton" idea)

  • java.lang.Integer#valueOf(int) (also on BooleanByteCharacterShortLong and BigDecimal)

Proxy (recognizeable by creational methods which returns an implementation of given abstract/interface type which in turndelegates/uses a different implementation of given abstract/interface type)

  • java.lang.reflect.Proxy
  • java.rmi.*
  • javax.ejb.EJB (explanation here)
  • javax.inject.Inject (explanation here)
  • javax.persistence.PersistenceContext

Behavioral patterns

Chain of responsibility (recognizeable by behavioral methods which (indirectly) invokes the same method inanother implementation of same abstract/interface type in a queue)

  • java.util.logging.Logger#log()
  • javax.servlet.Filter#doFilter()

Command (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been encapsulated by the command implementation during its creation)

  • All implementations of java.lang.Runnable
  • All implementations of javax.swing.Action

Interpreter (recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type; note that parsing/formatting is not part of the pattern, determining the pattern and how to apply it is)

  • java.util.Pattern
  • java.text.Normalizer
  • All subclasses of java.text.Format
  • All subclasses of javax.el.ELResolver

Iterator (recognizeable by behavioral methods sequentially returning instances of a different type from a queue)

  • All implementations of java.util.Iterator (thus among others also java.util.Scanner!).
  • All implementations of java.util.Enumeration

Mediator (recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the command pattern) which delegates/uses the given instance)

  • java.util.Timer (all scheduleXXX() methods)
  • java.util.concurrent.Executor#execute()
  • java.util.concurrent.ExecutorService (the invokeXXX() and submit() methods)
  • java.util.concurrent.ScheduledExecutorService (all scheduleXXX() methods)
  • java.lang.reflect.Method#invoke()

Memento (recognizeable by behavioral methods which internally changes the state of the whole instance)

  • java.util.Date (the setter methods do that, Date is internally represented by a long value)
  • All implementations of java.io.Serializable
  • All implementations of javax.faces.component.StateHolder

Observer (or Publish/Subscribe) (recognizeable by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state)

  • java.util.Observer/java.util.Observable (rarely used in real world though)
  • All implementations of java.util.EventListener (practically all over Swing thus)
  • javax.servlet.http.HttpSessionBindingListener
  • javax.servlet.http.HttpSessionAttributeListener
  • javax.faces.event.PhaseListener

State (recognizeable by behavioral methods which changes its behaviour depending on the instance's state which can be controlled externally)

  • javax.faces.lifecycle.LifeCycle#execute() (controlled by FacesServlet, the behaviour is dependent on current phase (state) of JSF lifecycle)

Strategy (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been passed-in as method argument into the strategy implementation)

  • java.util.Comparator#compare(), executed by among others Collections#sort().
  • javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the implementor has to process them (and not to get hold of them as instance variables!).
  • javax.servlet.Filter#doFilter()

Template method (recognizeable by behavioral methods which already have a "default" behaviour definied by an abstract type)

  • All non-abstract methods of java.io.InputStreamjava.io.OutputStreamjava.io.Readerand java.io.Writer.
  • All non-abstract methods of java.util.AbstractListjava.util.AbstractSet and java.util.AbstractMap.
  • javax.servlet.http.HttpServlet, all the doXXX() methods by default sends a HTTP 405 "Method Not Allowed" error to the response. You're free to implement none or any of them.

Visitor (recognizeable by two different abstract/interface types which has methods definied which takes each the otherabstract/interface type; the one actually calls the method of the other and the other executes the desired strategy on it)

  • javax.lang.model.element.AnnotationValue and AnnotationValueVisitor
  • javax.lang.model.element.Element and ElementVisitor
  • javax.lang.model.type.TypeMirror and TypeVisitor
  • java.nio.file.FileVisitor and SimpleFileVisitor
  • javax.faces.component.visit.VisitContext and VisitCallback

Leave a Comment

1 . Useful Java Annotations?

Answer :

I doled out a bunch of upvotes for other users, but just to give my two cents the only three annotations I use with any regularity in development are the main annotations used directly by the compiler:

@Override - Great for making it explicit in your code when you're overriding another method. Also has the extra benefit of being flagged as a compilation error if you don't override a method the way you think you are (see this other SO post). This flag informs the compiler that you're intending to override something, so if you don't (e.g. you forget an argument in the method signature), the compiler will catch it.

@Deprecated - Indicate whatever you're marking as something that should not be used from this point forward. The compiler will generate warnings for use of any code elements you've marked as deprecated. In general, deprecation says "this was in here in the past, but it may go away in a future version." Make sure you also use the associated "@deprecated" Javadoc flag in conjunction with this too to tell people what they should use instead.

@SuppressWarnings - Tell the compiler to suppress specific warnings it would otherwise generate. This can be useful for things like when you intentionally want to use deprecated methods, you can block out the deprecation warning. I tend to use it a lot to block out everyone's favorite "Serialization UID" warning on serializable classes (whether or not you should do that is another debate for another time). Just handy for those cases where you know something you're doing is generating a warning, but you're 100% sure it's the proper behavior you want.

Look at the Sun Annotations Guide and check out the section "Annotations Used by the Compiler". These three are given a fairly lengthy discussion.

2 . How to determine the optimal number of java threads when using a hyperthreaded multi core CPU?

Answer :

The ideal number of threads depend on the task itself. Context switching in modern CPU's can be somewhat expensive due to the fact that data used in the computation is cached heavily. Consider the situation where there are no IO related activities and the CPU cycles need not be wasted waiting. Then the maximum throughput would be achieved by having n_threads = n_cores. Context switching might be expensive even when hyper threading is available. But if there are IO activities, increasing the thread count beyond the number of cores can benefit.



3 . The enhanced forstatement?

Answer :

You don't get an index in an enhanced for-loop. you get a reference to the value in the containeryou are iterating. So, you can directly print it.

Change the below statement in your 1st snippet:




For your 2nd snippet, this:

for (int g: greeting)

doesn't make sense at all. As I said, you get the copy of reference to the elements in greeting, and since the element in greeting are of type String, your loop variable should be String g as in first snippet.

4 . Some basic questions about javax vs java packages?

Answer :

I think it's fairly arbitrary. As Jon Skeet says in his answer to the question you link to, much of it historical. A good example of this is javax.sql - it contains classes to do with JDBC that were originally part of J2EE, but which were brought into J2SE in 1.4. So now there is a pointless split of classes between java.sql and javax.sql. There's no particular meaning attached to the java/javax split inside the JDK.

  1. The CORBA classes are where they are because they aren't defined by the Java standard; they're translations of interfaces defined in the CORBA specifications.
  2. There are plenty of javax.* packages that come with the standard J2SE JDK/JRE (javax.sql, javax.xml). There are also javax.* packages which don't (javax.inject, javax.servlet, etc). But there are no java.* packages which are not in the JDK.
  3. I believe the bootstrap classloader loads java.* and javax.* classes alike.

5 . Java jsr310: difference between dates and times?

Answer :

Answering wrt to the final JDK1.8 version.

There are two amount classes - Duration and Period. Duration is time-based (nanos) and Period is date-based (year/month/day).

The amount of time between two temporal objects of the same type can be easily calculated in one of two ways (I prefer the first):

long days = ChronoUnit.DAYS.between(start, end);
long days = start.until(end, ChronoUnit.DAYS);

The Duration between two temporal objects of the same type can be calculated as follows:

Duration d = Duration.between(start, end);

The Period between two LocalDate objects can be calculated as follows:

Period p = Period.between(start, end);

6 . Make getSystemService() recognize our new system service?

Answer :

Are these 2 files the same? or is it just missing(the content/app folder)?

These are the same files.

Any idea on what to do?

As I said the implementation has been changed. I looked into the code and here what you can change to make your code working (I can only suppose because I did not actually build my code). In the static block of ContextImpl class you need to add the following code:

registerService(ACCOUNT_SERVICE, new ServiceFetcher() {
    public Object createService(ContextImpl ctx) {
        IBinder b = ServiceManager.getService(OPERSYS_SERVICE);
        IOpersysService service = IOpersysService.Stub.asInterface(b);
        return new OpersysManager(service);

7 . Core reading resources for Java Multithreading / Concurrency? [closed]?

Answer :

I propose you something slightly different: Programming Concurrency on the JVM.

This will explain to you the different models and the different problems with concurrency on the JVM. Not entirely targeted at Java, but at the JVM ecosystem, it will give you a deep understanding, along with the technical tools.

8 . Dual-core CPU utilization w/ single Java thread running [duplicate]?

Answer :

When the OS executes threads, it runs each thread for a certain period of time (say 10-20ms), then saves the state of the thread, and looks for other threads to run.

Now, despite what you might think from looking at the CPU Utilization graph, the OS is actually running a lot more threads than those from your program. There are threads running UI loops, threads waiting on I/O, threads running background services, etc. Most of the threads spend most of their time blocked waiting on something.

The reason why I'm talking about this is to explain that from OS's point of view, the situation is more complex than it might look. There are a whole bunch of threads doing a whole bunch of things, and the OS is attempting to switch between them. Suppose that you wanted to implement a heuristic that if a thread used up its entire quantum the last time, then the OS will make an effort to schedule it to the same core. The OS needs to track and take into account more information, and the success of the optimization may depend on a lot of hard-to-predict factors.

In addition, the benefit of affinitizing a thread to a core are often negligible in practice, so OSes don't attempt to do it automatically. Instead, they expose a feature that allows the developer to explicitly say that a particular thread should be affinitized to a core, and then the OS will respect the decision.

That seems like a reasonable trade-off: if your thread performs better when affinitized to a core, just ask the OS to do that. But, the OS won't bother attempting to figure it out for you.

9 . Generic programming in java?

Answer :

If the above were true, then you could take your collection of managers, treat it as a collection of employees, and then put any employee into a collection of managers (i.e. not just a manager, but a (say) graduate trainee, a CIO etc.)

It's a little counter-intuitive. An orange is a fruit. A list of oranges is not a list of fruit (otherwise you could put an apple in it). There's a concise explanation in the Java Generics Tutorial.

10 . Cant compile and run java code in IntelliJ IDEA?

Answer :

Sergey, it's look like you are working wrong with Idea. There is a step-by-step tutorial at wiki, that describes some basic concepts, about roots, run configurations, sdk-s and dependencies. It will be good, if you look at it. (Exploring the project structure and Building(Running) the projectespecially)

IDE is a great helper to learn language, especially such intellegent one, as Idea, so, it will be a good start, to get familiar with it.

Basically, for a start, all your code(not compiled classes) must be under the source roots, and runConfiguration must specify application entry point (class with static void main() method).

You shouldn't think about class files, jar archives or command line tools, IDEA can do all this for you.

Better concentrate on learning, as I think!

11 . Java: How to scale threads according to cpu cores?

Answer :

You can determine the number of processes available to the Java Virtual Machine by using the static Runtime method, availableProcessors. Once you have determined the number of processors available, create that number of threads and split up your work accordingly.

Update: To further clarify, a Thread is just an Object in Java, so you can create it just like you would create any other object. So, let's say that you call the above method and find that it returns 2 processors. Awesome. Now, you can create a loop that generates a new Thread, and splits the work off for that thread, and fires off the thread. Here's some psuedocode to demonstrate what I mean:

int processors = Runtime.getRuntime().availableProcessors();
for(int i=0; i < processors; i++) {
  Thread yourThread = new AThreadYouCreated();
  // You may need to pass in parameters depending on what work you are doing and how you setup your thread.

12 . Why is (a*b != 0) faster than (a != 0 && b != 0) in Java?

Answer :


I'm ignoring the issue that your benchmarking might be flawed, and taking the result at face value.

Is it the compiler or is it at the hardware level?

That latter, I think:

  if (a != 0 && b != 0)

will compile to 2 memory loads and two conditional branches

  if (a * b != 0)

will compile to 2 memory loads, a multiply and one conditional branch.

The multiply is likely to be faster than the second conditional branch if the hardware-level branch prediction is ineffective. As you increase the ratio ... the branch prediction is becoming less effective.

The reason that conditional branches are slower is that they cause the instruction execution pipeline to stall. Branch prediction is about avoiding the stall by predicting which way the branch is going to go and speculatively choosing the next instruction based on that. If the prediction fails, there is a delay while the instruction for the other direction is loaded.

(Note: the above explanation is oversimplified. For a more accurate explanation, you need to look at the literature provided by the CPU manufacturer for assembly language coders and compiler writers. The Wikipedia page on Branch Predictors is good background.)

However, there is one thing that you need to be careful about with this optimization. Are there any values where a * b != 0 will give the wrong answer? Consider cases where computing the product results in integer overflow.


Your graphs tend to confirm what I said.

  • There is also a "branch prediction" effect in the conditional branch a * b != 0 case, and this comes out in the graphs.

  • If you project the curves beyond 0.9 on the X-axis, it looks like 1) they will meet at about 1.0 and 2) the meeting point will be at roughly the same Y value as for X = 0.0.


I don't understand why the curves are different for the a + b != 0 and the a | b != 0 cases. There could be something clever in the branch predictors logic. Or it could indicate something else.

(Note that this kind of thing can be specific to a particular chip model number or even version. The results of your benchmarks could be different on other systems.)

However, they both have the advantage of working for all non-negative values of a and b.


13 . Start Instances of Java Program, Each on a Separate Core?

Answer :

I don't know of any way to attach instances of Java programs to specific CPUs / cores. As an alternative, consider making the program concurrent, i.e. start multiple executor threads internally. This way you need to run only a single instance of it, but its individual threads would run on distinct processors/cores if there are multiple available ones.

This in fact probably yields better performance and is more scalable than running multiple processes - the Executor framework allows you to choose different thread pools, change the number of threads even dynamically, manages dead threads for you etc.

14 . Oozie java-action does not include core-site.xml?

Answer :

The reason of that the core-site.xml is not included in the class-path of the java-action is because the property mapreduce.application.classpath points to the wrong directory:


It should point to


i.e, the full property should be something like, in mapred-site.xml:


15 . Integrate C and JAVA in Blackberry?

Answer :

You can't integrate C, as RIM does not expose any API for the platform. Since BlackBerry use a j2me-compliant JVM, JNI is not exposed.

Prior answer is partially correct - you may write code that uses only the J2ME API, but you can also use RIM's own Java API for better/more advanced features and functionality.