Sunday, January 23, 2011

FAQS on threads concept on JAVA


         Answer: Threaded programming is normally used when a program is required to do more than one task at the same time. Threading is often used in applications with graphical user interfaces; a new thread may be created to do some processor-intensive work while the main thread keeps the interface responsive to human interaction.
The Java programming language has threaded programming facilities built in, so it is relatively easy to create threaded programs. However, multi-threaded programs introduce a degree of complexity that is not justified for most simple command line applications. 

Question: What is a thread?

Answer: In Java the Thread class represents a single independent path of execution in a Java Virtual Machine. When you run a Java program it implicitly starts a single thread of execution. The Thread class enables programmers to create additional threads and set them running. A number of threads may run in parallel, but only one is actively executed at a given moment.
The Java runtime system uses fairly complex thread scheduling mechanisms to coordinate the execution of threads, but this does not require privileged knowledge or detail level intervention by programmers. Programmers can manage the high level creation, initiation and distribution of tasks amongst threads through simple Application Programming Interface (API) methods.
The example below shows the simplest approach to thread creation and task execution; construct a new Thread with a Runnable argument and start it.


Question: How do Java threads make the environment asynchronous?

Answer: The thread mechanism in Java begins with the main entry point thread the runtime environment creates to start a Java program. When you use that initial thread create secondary threads, each one runs independently of the other. The Java virtual machine manages the execution of the threads so they behave as if they all run at the same time, in fact each thread briefly takes turns at execution.
In its simplest form there may be no communication or synchronization between multiple threads in a Java program and they each run to completion independently of each other. In this respect Java threads are fundamentally asynchronous, there is no master clock that governs when threads will run and when they synchronize variables to “catch-up” with each other.
        It is often necessary and more useful if threads do check ready states before progressing, synchronize read and write access to shared variables and call-back to each other when their work is done. This is where the synchronized keyword and the various sleep(), wait() and notify() methods are used to more closely schedule the interaction between asynchronous threads.

Saturday, January 22, 2011

Example for thread in java

                 This example illustrates how to create a thread and how to implement the thread. In this example we will see that the program prints numbers from 1 to 10 line by line after 5 seconds which has been declared in the sleep function of the thread class. Sleep function contains the sleeping time in millisecond and in this program sleep function has contained 5000 millisecond mean 5 second time. There is sleep function must caught by the InterruptedException. So, this program used the InterruptedException which tells something the user if thread is failed or interrupted.

Here is the code of the program : 
 
public class Threads{
  public static void main(String args[]){
    Thread th = new Thread();
    System.out.println("Numbers are printing line by line after 5 seconds : ");
    try{
      for(int i = 1;i <= 10;i++)
      {
        System.out.println(i);
        th.sleep(5000);
      }
    }
    catch(InterruptedException e){
      System.out.println("Thread interrupted!");
      e.printStackTrace();
    }
  }
}
 

Wednesday, January 19, 2011

What is the difference between thread amd process?

Process:
                     A process is an instance of a computer program that is executed sequentially. It is a collection of instructions which are executed simultaneously at the run time. Thus several processes may be associated with the same program. For example, to check the spelling is a single process in the Word Processor program and you can also use other processes like printing, formatting, drawing, etc. associated with this program.

Thread:
                A thread is a lightweight process which exist within a program and executed to perform a special task. Several threads of execution may be associated with a single process. Thus a process that has only one thread is referred to as a single-threaded process, while a process with multiple threads is referred to as a multi-threaded process.

                  In Java Programming language,  thread is a sequential path of code execution within a program. Each thread has its own local variables, program counter and lifetime. In single threaded runtime environment, operations are executes sequentially i.e. next operation can execute only when the previous one is complete. It exists in a common memory space and can share both data and code of a program. Threading concept is very important in Java through which we can increase the speed of any application. You can see diagram shown below in which a thread is executed along with its several operations with in a single process.

Tuesday, January 18, 2011

Explain what is thread? and it's life cycle in java


A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

When you are programming with threads, understanding the life cycle of thread is very valuable. While a thread is alive, it is in one of several states. By invoking start() method, it doesn’t mean that the thread has access to CPU and start executing straight away. Several factors determine how it will proceed.

Different states of a thread are :


  1. New state – After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
         
  2. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.
         
  3. Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
         
  4. Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
  5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.

Saturday, January 15, 2011

Difference between an interface and an abstract class?

 An abstract class may contain code in method bodies, which is not allowed in an interface.
With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

Wednesday, January 12, 2011

sloution to ANT build error "error during FTP transfer: j ava.net.ConnectException: Connection refused: connect"

This is my personal experience, when I am tying to  access the Unix server through FTP, I got the below error:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

C:\ant_scripting\apache-ant-1.8.2\build.xml:20: Could not create type ftp due to java.lang.NoClassDefFoundError: org/apache/commons/net/ftp/FTPClientConfig at org.apache.tools.ant.taskdefs.optional.net.FTP$LanguageCode.getValidLanguageCodes(FTP.java:2693)
        at org.apache.tools.ant.taskdefs.optional.net.FTP$LanguageCode.(FTP.java:2689)
        at org.apache.tools.ant.taskdefs.optional.net.FTP.(FTP.java:135)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
        at org.apache.tools.ant.AntTypeDefinition.innerCreateAndSet(AntTypeDefinition.java:328)
        at org.apache.tools.ant.AntTypeDefinition.createAndSet(AntTypeDefinition.java:274)
        at org.apache.tools.ant.AntTypeDefinition.icreate(AntTypeDefinition.java:219)
        at org.apache.tools.ant.AntTypeDefinition.create(AntTypeDefinition.java:206)
        at org.apache.tools.ant.ComponentHelper.createComponent(ComponentHelper.java:286)
        at org.apache.tools.ant.ComponentHelper.createComponent(ComponentHelper.java:264)
        at org.apache.tools.ant.UnknownElement.makeObject(UnknownElement.java:417)
        at org.apache.tools.ant.UnknownElement.maybeConfigure(UnknownElement.java:163)
        at org.apache.tools.ant.Task.perform(Task.java:347)
        at org.apache.tools.ant.Target.execute(Target.java:390)
        at org.apache.tools.ant.Target.performTasks(Target.java:411)
        at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
        at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
        at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
        at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
        at org.apache.tools.ant.Main.runBuild(Main.java:809)
        at org.apache.tools.ant.Main.startAnt(Main.java:217)
        at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
        at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
solution which I have find to avoid this error was given below:

1. To run FTP command  by using ant script, you must have to down load the commons-net-1.4.1.jar file.
  click here to down load the file, please make sure to download the jar file according to your JAVA version,
Find more details on the Apache  link.
2. please make sure to put the jar file in the class path. and run the script, oops you won't get any error now.

please put your comment in case of any issues.            




Wednesday, November 10, 2010

String, StringBuffer & stringBuilder in JAVA

1] Differnces between the above three is:
   String is immutable
   StringBuffer & StringBuilders are mutable.

2] Differnces between the StringBuffer& stringBuiler:
   StringBuffer is synchronized.
   StringBuilder is unsynchronized.

3] On which scenario we have to use the above three?
   String: If the text is not going to change use a string Class because a String object is    immutable.
   StringBuffer: If the text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.
   StringBuilder : If the text can change and will only be accessed from a single thread, then use StringBuilder because StringBuilder is unsynchronized.

Sunday, July 4, 2010

Setting the class path to JAVA on Windows XP and 2000

Setting the class path to JAVA on Windows XP &2000

• Open the System Properties window (by right-clicking on My Computer and selecting Properties, or through the Control Panel - Start -> Control Panel -> System).
• On the Advanced tab, click the Environment Variables button.
• In user variables, select the new tab and give the variable name as JAVA_HOME and value as path of the java folder (Example: C:\Java)
• In System variables we have to set the CLASSPATH; if it is already exists then add the java path up o lib folder (Example C:\Java\lib)

Sunday, February 24, 2008

STRUTS FAQS

Struts

Struts is a open source framework which make building of the web applications easier based on the java Servlet and JavaServer pages technologies.

Struts framework was created by Craig R. McClanahan and donated to the Apache Software Foundation in 2000. The Project now has several committers, and many developers are contributing to overall to the framework.

Developing web application using struts frame work is fairly complex, but it eases things after it is setup. It encourages software development following the MVC design pattern. Many web applications are JSP-only or Servlets-only.
With JSP and Servlets, Java code is embedded in the HTML code and the Java code calls println methods to generate the HTML code respectively. Both approaches have their advantages and drawbacks; Struts gathers their strengths to get the best of their association.

Struts is based on Model-View-Controller (MVC) design paradigm, it is an implementation of JSP Model 2 Architecture. For more of Model-View-Controller (MVC) click here.

Consists of 8 Top-Level Packagesand approx 250 Classes and Interfaces.

Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. This definition implies that Struts is a framework, rather than a library, but Struts also contains an extensive tag library and utility classes that work independently of the framework.

The overview of struts

Client browser
An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response.

Controller
The controller is responsible for intercepting and translating user input into actions to
be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations.The Controller receives the request from the browser, and makes the decision where to send the request. With Struts, the Controller is a command design pattern implemented as a servlet. The struts-config.xml file configures the Controller.


Business logic
The business logic updates the state of the model and helps control the flow of the application. With Struts this is done with an Action class as a thin wrapper to the actual business logic.

Model
A model represents an application’s data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags.

View
The view is responsible for rendering the state of the model. The presentation semantics are encapsulated within the view, therefore model data can be adapted for several different kinds of clients.The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller.The view is simply a JSP file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the things that make Struts unique compared to other frameworks like Velocity.

SERVLET FAQS

Q: What's the difference between applets and servlets?

A: There are many fundamental differences between Applet and Servlet classes, the Java API documentation for the two types will show you they have little in common.

Applets are essentially graphical user interface (GUI) applications that run on the client side in a network environment, typically embedded in an HTML page. Applets are normally based on Abstract Windowing Toolkit components to maintain backward-compatibility with the widest range of browsers' Java implementations. The application classes are downloaded to the client and run in a Java Virtual Machine provided by the browser, in a restrictive security environment called a "sandbox".

Servlets are used to dynamically generate HTTP responses and return HTML content to Web browsers on the server side. Servlets are often used to validate and process HTML form submissions and control a series of user interactions in what is known as a Web application. Servlets can be used to control all aspects of the request and response exchange between a Web browser and the server, called a servlet container.

JDBC FAQS:

JSP FAQS:

What are the implicit objects? - Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response, pageContext, session, application, out, config, page, exception.

Is JSP technology extensible? - Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use . You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe

How does JSP handle run-time exceptions? - You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

How do I prevent the output of my JSP or Servlet pages from being cached by the browser? - You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.

How do I use comments within a JSP page? - You can use “JSP-style” comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example:

--%>
You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:

CORE JAVA FAQS.............

Java is an object-oriented programming language developed by Sun Microsystems. Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level, which means that Java programs (applets and applications) can run on any machine that has the Java virtual machine installed.

Java is Platform independent, Platform independence means, the ability of a program to move easily from one computer system to another-is one of the most significant advantages that Java has over other programming languages, particularly if your software needs to run on many different platforms.

The Java language was developed at Sun Microsystems in 1991 as part of a research project to develop software for consumer electronics devices. Java's rapidly growing popularity is due to the Web. But Java's inherent power does not come from the fact that it is a Web programming language. The talented software engineers at Sun, in bringing Java to the Web, have elegantly solved a much broader and more significant problem-how to develop network-capable windowing software that will run on almost any 32-bit computer and operating system.

A software developer writes programs in the Java language that use predefined software packages of the Java API. The developer compiles his or her programs using the Java compiler. This results in what is known as compiled bytecode. Bytecode is in a form that can be executed on the Java virtual machine, the core of the Java runtime system. You can think of the virtual machine as a microprocessor that is implemented in software and runs using the capabilities provided by your operating system and computer hardware. Since the Java virtual machine is not a real microprocessor, the Java bytecode is interpreted, rather than executed directly in the native machine instructions of the host computer.





Java is exceptionally well suited to distributed networking applications because of its built-in networking support and the runtime system's capability to dynamically load Java bytecode across the network. Java also provides the capability to dynamically utilize new content and protocol handling software. The HotJava browser, written in Java, is an excellent example of Java's distributed networking capabilities.

The Java API provides full support of multithreaded programming. Multithreaded programs can be developed in a single, consistent manner, independent of the vagaries of the host operating system interface.

Java classes and objects directly support the object-oriented concepts of encapsulation, inheritance, messages and methods, and data hiding. Java interfaces provide support for multiple inheritance and polymorphism. The Java language retains all the benefits of object-oriented programming without the performance impacts associated with pure object languages, such as Smalltalk.

The Java API provides extensive support of windowing and graphical user interface development without the complexities associated with maintaining multiple window class libraries. Several visual programming tools have been developed for Java.