Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, September 2, 2010

Java Threads : Using Callable

                      Threads , the first thing which comes to mind is the Runnable Interface. Callable is an interface introduced in Java 5 to take care of this specific requirement. Callable is similar to Runnable, but it returns a value.  A Future interface holds the result of asynchronous computation and it is used in conjunction with Callable. FutureTask is a wrapper class which implements both Future and Runnable interfaces and it provides a convenient way to convert a Callable into both a Future and a Runnable.

Lets see an example which implements the same:


Make a StringGenerator Class:

import java.util.concurrent.Callable;
import static java.lang.Math.random;

public class StringGenerator implements Callable {

    public String call() throws Exception {
        String [] allStrings =
                {"Wine", "Movies", "Party", "Books", "Shopping",
                "Flowers", "Food", "Music", "Cars","Jewelery"};
        int index = (int)(random()*100)/10;

        //Let's wait for sometime
        Thread.sleep(2000);
        return allStrings[index];
    }
}


Next make a StringGeneratorTest class:

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;


public class StringGeneratorTest {

    public static void main(String[] args) {

        //Create an array to store the future objects.
        ArrayList> results = new ArrayList>();
        for (int i=0; i<10; i++){
            //Create the instance of the Callable task
                        Callable stringGenerator = new StringGenerator();

            //create the object of FutureTask
            FutureTask task =
                                new FutureTask(stringGenerator);

            //Add to the list
            results.add(task);

            //Create a thread object using the task object created
            Thread t = new Thread(task);

            //Start the thread as usual
            t.start();

        }

        //Compute the results now.
        StringBuilder resultStr = new StringBuilder();

        long start = System.currentTimeMillis();

        for(Future result: results){
            try {
                //The blocking get call
                resultStr.append(result.get());
                resultStr.append(" ");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        long end = System.currentTimeMillis();

        System.out.println("The returned string is:\n"+resultStr);
        System.out.println("Execution time:"+(end - start));
    }
}

Output:
The returned string is:
Shopping Party Party Flowers Books Wine Wine Flowers Music Cars
Execution time:1002

Explanation:
Create a StringGenerator thread which is supposed to return a random string to the caller. Create a StringGeneratorTest class which spawns ten StringGenerator thread and displays the concatenation of the string returned from all the threads.


Hope this helped !!! Cheers !! :-)

References:

Thursday, August 19, 2010

Removing Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory!!

Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory
at org.apache.catalina.startup.Bootstrap.(Bootstrap.java:54)
Caused by: java.lang.ClassNotFoundException: org.apache.juli.logging.LogFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:336)
… 1 more
Could not find the main class: org.apache.catalina.startup.Bootstrap. Program will exit.

Solutions

1. In Eclipse, Open the “Server” tab.
2. Double click on the “Tomcat6″ entry to see the configuration.
3. Then click on the “Open launch configuration” link in the “General information” block.
4. In the dialog, select the “Classpath” tab.
5. Click the “Add external jar” button.
6. Select the file “/usr/share/tomcat6/bin/tomcat-juli.jar”
7. Close the dialog.
8. Start tomcat 6 from Eclipse.

Thursday, June 17, 2010

Rmoving Restrictions on package like sun.*, java.*

The java.*, javax.* and org.* packages documented in the Java Platform Standard Edition API Specification make up the official, supported, public interface. If a Java program directly calls only API in these packages, it will operate on all Java-compatible platforms, regardless of the underlying OS platform.
The sun.* packages are not part of the supported, public interface.
A Java program that directly calls into sun.* packages is not guaranteed to work on all Java-compatible platforms. In fact, such a program is not guaranteed to work even in future versions on the same platform.


Due to the same a project give access restriction errors at the compile time ...
Access restriction: Class is not accessible due to restriction on required library";
may be shown while developing Java projects in Eclipse IDE.

Solution: follow the following steps to solve the same

1.(Your Project) Properties -> Java Compiler -> Errors/Warnings


This was all about eclipse when you deploy the same using Felix
you can either pass the VM argument as:

-Dorg.osgi.framework.bootdelegation=sun.*,com.sun.*

or you can add

Dorg.osgi.framework.bootdelegation=sun.*,com.sun.*

in the config.properties file in the conf folder of the Felix Framework





References:

1 http://java.sun.com/products/jdk/faq/faq-sun-packages.html
2 http://lkamal.blogspot.com/2008/09/eclipse-access-restriction-on-library.html
3 http://blog.springsource.com/2009/01/19/exposing-the-boot-classpath-in-osgi/





Friday, June 4, 2010

eqinox to felix - an experience

The other day I had created a few OSGi bundles in Eclipse and deployed the same in the Equinox framework of Eclipse..

These same bundles when I deployed in Felix.. it gave an error stating it was not able to find the classes .. esp those which were exposing the services.Next I added the following bundles in the manifest of each of the bundles:

- javax.naming
- javax.naming.event
- javax.naming.spi


And VOILA !!! it worked .... :-)

Thursday, May 27, 2010

Happy Eclipse working-IDE Shortcuts

Since long I have been using Eclipse , now I realize the necessity of using shortcuts.
Not only does it save time at the same time enriches the coding experience .
I have mentioned them here below :




Navigational Shortcuts


F10


Main menu:


Shift F10 -----------------
Context menu
Ctrl F10
-----------------View menu

Workspace navigation:


F12 -----------------
Activate editor
Ctrl+Shift+W----------
Switch editor
Ctrl F6---------------
Next editor
Ctrl Shift F6-----------
Prev editor
Ctrl F7---------------
Next workspace
Ctrl Shift F7-----------
Prev workspace
Ctrl F8
----------------Next perspective
Ctrl Shift F8 -----------
Prev perspective
Alt Left----------------
Back
Alt Right -------------
Forward

Files:


Alt Shift S -----------------
Show in…
Ctrl Shift R-----------------
Jump to file
Ctrl N ----------------------
New file
Ctrl S ----------------------
Save file
Ctrl Shift S -----------------
Save all files
Ctrl F4---------------------
Close file
Ctrl Shift F4-----------------
Close all files

Find:


Ctrl L -----------------
Goto line
Ctrl F -----------------
Find
Ctrl J-----------------
Incremental find
Ctrl Shift J -------------
Incremental find prev
Ctrl K -----------------
Find next
Ctrl Shift K -------------
Find prev
Ctrl H ------------------
Search workspace
Ctrl (dot)---------------
Navigate next
Ctrl (comma) ------------
Navigate prev

Java navigation:


F3---------------------
Goto declaration
Ctrl Shift U --------------
Find references in file
Ctrl Shift G---------------
Find references in workspace
Ctrl G ------------------
Find declarations in workspace
Ctrl Shift P---------------
Navigate to matching bracket/brace
Ctrl T--------------------
Popup type hierarchy
Ctrl Shift T ----------------
Open Type
Ctrl O--------------------
Outline of current source
Ctrl F3-------------------
Outline of current cursor position
Ctrl Shift Arrow ------------
Jump beetween methods up or down
F2 ----------------------
Show Javadoc
F4 ----------------------
Show hierarchy
Ctrl Alt H -----------------
Open call hierarchy


General editing:


Alt Arrow -----------------
Move line(s) up or down
Alt Shift Up ---------------
Expand selection to enclosing element
Alt Shift Right -------------
Expand selection to next element
Alt Shift Left---------------
Expand selection to previous element
Alt Shift Down--------------
Restore previous selection
Ctrl Alt Arrow---------------
Duplicate line(s) up or down
Shift Enter -----------------
Insert line below
Ctrl Shift Enter -------------
Insert line above
Ctrl D ---------------------
Delete line
Ctrl Shift Q -----------------
Toggle Quick Diff
Ctrl Shift Y -----------------
Convert to lowercase
Ctrl Shift X -----------------
Convert to uppercase

Java editing:


Alt Shift U -----------------
Remove occurrence annotations
Ctrl 1----------------------
Quick fix (works even when there are no errors
Ctrl Shift M -----------------
Add import
Ctrl Shift F ------------------
Reformat
Ctrl Shift O------------------
Organize Imports
Ctrl / -----------------------
Comment
Ctrl \ -----------------------
UnComment
Ctrl Shift Space--------------
Parameter hints
Ctrl ------------------------
Hyperlink identifier
Ctrl I-----------------------
Correct indentation
Shift Space -----------------
Incremental content assist

Debugger :


F5 ----------------------
Step into
F6 ----------------------
Step over
F7
----------------------Run to return
F8 ----------------------
Resume
F9 ----------------------
Relaunch last
F11 ---------------------
Run/debug last
Ctrl F11------------------
Run
Ctrl Shift B ---------------
Toggle breakpoint
Ctrl D
-------------------Display
Ctrl Q --------------------
Inspect
Ctrl R--------------------
Run to line
Ctrl U --------------------
snippet




Refactoring:


Alt T ----------------------
Refactoring menu
Ctrl Shift Z ------------------
Undo refactor
Ctrl Shift Y------------------
Redo refactor
Alt Shift R ------------------
Rename
Alt Shift V -------------------
Move
Alt Shift I--------------------
Inline
Alt Shift M-------------------
Extract method
Alt Shift L-------------------
Extract local
Alt Shift C------------------
Change method signature

Misc:


F5 ------------------
Refresh
F1 ------------------
Infopop
F2 ------------------
Show resizeable hover


Go try and have fun !!