Monday, August 11, 2014

JAVA OO design hints

How to identify classes?
 - Look for nouns in the problem analysis . This could be good candidates as class
 -  Look for verbs in the problem analysis, this could be good candidates as method

Relationships between classes:
 - Dependence =>  "uses a"
 - Aggregation =>  "has a"
 - Inheritance  => "is a"

Class Design Hints:
1. Always keep data private

2. Always initialize data

3. Don't use too many basic types in a class
  - Replace multiple related uses of basic types with other classes. This keeps your classes easier to understand and to change.
4. Not all fields need individual field accessors and mutators.

5. Break up classes that have too many responsibilities

6. Make the names of your classes and methods reflect their responsibilities.

Inheritance Hints:
1. Apply "is-a"
2. It is best to minimize the use of casting and the instanceof operator.
3. In practice use protected fields with caution and try to avoid it because it is against the spirit of OOP, which encourages data encapsulation.
3. Protected method makes more sense. A class may declare a method as protected if it is tricky to use. This indicates that the subclass can be trusted to use this method correctly, but other classes are not trusted to use this method.

Summary of JAVA access modifiers that control visibility:
1. visible to the class only => private
2. visible to the world  => public
3. visible to the package and all sub classes => protected
4. visible to the package => default, No modifiers are required.

Design hints for OO inheritance
1. Place common operations and fields in the super class
2. Don't use protected fields  => This can break OO encapsulation. a. any subclass can access/modify such fields; b. Any class in the same package can access/modify such fields
3. Use inheritance to model "is-a" relationship.
4. Don't use inheritance unless all inherited methods make sense.
5. Don't change the expected behavior when you override a method. => this violates the substitution principle.
6. Use polymorphism, not type information => avoid instanceof as much as possible
7. Don't overuse reflection  => Extremely useful for system programming , but it is not appropriate for applications. Reflection is fragile.






Sunday, July 13, 2014

Difference between Callable and Runnable in Java

Difference between Callable and Runnable interface in Java is one of the interesting question from my list of Top 15 Java multi-threading questions, and it’s also very popular in various Java Interviews. Callable interface is newer than Runnable interface and added on Java 5 release along with other major changes e.g. Generics, Enum, Static imports and variable argument method. Though both Callable and Runnable interface are designed to represent task, which can be executed by any thread, there is some significant difference between them. In my opinion, major difference between Callable and Runnable interface is that Callable can return result of operation performed inside call() method, which was one of the limitation with Runnable interface. Another significant difference betweenRunnable and Callable interface is ability to throw checked exception.Callable interface can throw checked exception because it's call method throws Exception. By the way sometime this question is also asked as follow-up question of another classic difference between Runnable and Thread in Java. Commonly FutureTask is used along withCallable to get result of asynchronous computation task performed in call() method.


Callable vs Runnable interface

Difference between Runnable and Callable in JavaAs I explained major differences between Callable and Runnable interface in last section. Sometime this question is also asked as difference between call() and run()  method in Java. All the points discussed here is equally related to that question as well.  Let's see them in point format for better understanding :


1) Runnable interface is older than Callable, there from JDK 1.0, while Callable is added on Java 5.0.
2) Runnable interface has run() method to define task while Callable interface uses call() method for task definition.
3) run() method does not return any value, it's return type is void while call method returns value. Callable interface is a generic parameterized interface and Type of value is provided, when instance of Callable implementation is created.

4) Another difference on run and call method is that run method can not throw checked exception, while call method can throw checked exception in Java.


public class RunnableTest implements Runnable {
              @Override
              public void run() {
                         //any processing
              }
}
import java.util.concurrent.Callable;


public class CallableTest implements Callable { 
          @Override 
           public String call() throws Exception { 
                      // any processing
                    return new String("I am Callable and can return value and throw checked exception"); 
              } 
}

How to Stop Thread in Java

Thread is one of important Class in Java and multi-threading is most widely used feature,but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default a Thread stops when execution of run() method finish either normally or due to any Exception.In this article we will How to Stop Thread in Java by using a boolean State variable or flag. Using flag to stop Thread is very popular way  of stopping thread and its also safe, because it doesn't do anything special rather than helping run() method to finish it self.


How to Stop Thread in Java


How to Stop Thread in Java Tutorial Example
As I said earlier Thread in Java will stop once run() method finished. Another important point is that you can not restart a Thread which run() method has finished already , you will get an IllegalStateExceptio, here is a Sample Code for Stopping Thread in Java:








Sample Code to Stop Thread in Java



public class Runner extends Thread{
    boolean bStopMe= false;
  
    public void exit(){
        this.bStopMe= true;
    }

// or
   public void tellMeToStop() {
    bStopMe= true;
  }

    @Override
    public void run(){
        while(!bStopMe){
            System.out.println("Thread is running");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadTester.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
    }

}
    
    

Should we make bExit Volatile
Since every Thread has its own local memory in Java its good practice to make bStopMevolatile because we may alter value of bStopMefrom any thread and making it volatile guarantees that Runner will also see any update done before making bExit.

That’s all on how to stop thread in Java , let me know if you find any other way of stopping threads in Java without using deprecated stop() method.


Q: I have been wondering why isn't there a method to kill a waiting, sleeping or a non running thread. Is there anyway we can do that?

A: The reason you can't just stop a thread is actually fairly simple. What if it's allocated resources, and is in the middle of work? If you do a hard stop, that may just leave a lot of stuff hanging. So, instead you basically send it a message and it stops at it's own convenience (if implemented properly). Basically they pushed back that part of the behavior to the programmers.




Saturday, July 12, 2014

Difference between Thread and Runnable interface in Java

Thread vs Runnable in Java is always been a confusing decision for beginners  in java. Thread in Java seems easy in comparison of Runnable because you just deal with one class java.lang.Thread while in case of using Runnable to implement Thread you need to deal with both Thread and Runnable two classes. though decision of using Runnable or Thread should be taken considering differences between Runnable and Thread and pros and cons of both approaches. This is also a very popular thread interview questions and most of interviewer are really interested to know what is your point of view while choosing Thread vs Runnable or opposite. In this java article we will try to point out some differences between Thread and Runnable in Java which will help you to take an informed decision.


Thread vs Runnable in Java


Here are some of my thoughts on whether I should use Thread or Runnable for implementing task in Java, though you have another choice as "Callable" for implementing thread which we will discuss later.

1) Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.

2) In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread than use Runnable interface instead.

3) Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.

4) Separating task as Runnable means we can reuse the task and also has liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner.

5) Java designer recognizes this and that's why Executors accept Runnable as Task and they have worker thread which executes those task.

6) Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.

These were some of notable difference between Thread and Runnable in Java, if you know any other differences on Thread vs Runnable than please share it via comments. I personally use Runnable over Thread for this scenario and recommends to use Runnable or Callable interface based on your requirement


Tuesday, July 8, 2014

How to write production quality code?

How to write production quality code?
We often here the term "production quality code" , some times in interview where interviewee asked to write production quality code for a particular function,Some time discussion between developers and programmers and some time during code review. I know most of you familiar with term but for those who wonder what is production quality code in simple terms its code which can bear the test of time in production environment.

We all develop code in development, than test in QA and finally it gets released in production. But there are lot of difference between test and prod and if you have not coded taking prod environment in mind most likely code will fail in prod or result in exceptions.So what makes production environment different than development environment? Here are few things which I noted:


1) Production is all about load which will expose concurrency issues, load issues, memory and CPU issues.

2) You will get a lot many scenarios in production that you might have thought in development. If think through process is not applied than most likely those scenario has not handled in production.

3) Different data input or incorrect data, one of classic problems in production is the data which gets input to your program, be it from upstream system or any other place you will get all sort of data and if your program doesn't handle those very likely it will suffer.

4) Boundary conditions, this is some what related to above point data and scenarios but most of the boundary condition e.g. null, empty etc exposed in production.


So if a code is written all these things and potentially domain specific things and can sustain test of production than it called a production quality code and believe me it takes a lot of experience, skill and think through process to write production quality code not just in first time even after two or three iteration but as a developer we should always strive for writing production quality code in first attempt.

Now let's see how we can do that, what are the things we should keep in mind:

1) Get your requirements right, understand the problem , talk to user or business person as much as possible this will help you to find different scenario as early as possible. Many times business or user not tell you everything its not there fault but it doesn't come in mind right through. So if you are frequently speaking, discussing and presenting solution to them most likely they will ask questions, give feedback which eventually expose more scenario and subtle details. Here experience plays an important role. More experience or domain knowledge you, much better code you will write.

2) Think through, Think through and Think through. There is no substitute of this, it is more of a skill and art than science but you will get hold of this when you get more experience. For example if user says that you need replay capability in your program. You should be able to think of all possible scenarios where you need to replay and what could be required for that, what would be side effect of that. Does replay would be requested, what if the requesting system went down again, will you be able to re replay etc.

3) Boundary condition, always think that you will get bad input , you will get null or empty, small or very large numbers, function may get called at wrong time etc. you can get rid of this by writing unit test for each boundary condition.

4) Concurrency, this is is the major culprit and big problem which exposes itself in production when due to load multiple thread gets triggered and access your program concurrently. With high speed low latency electronic trading system and with many other java system where its requirement to have a concurrent application this can only be addressed by proper design , if you get the design right you will safe other wise you will need to bear the pain of redesigning or rewriting code. You can also expose concurrency issue by doing load testing in early QA cycles.

5) Exception handling, this is by far most important characteristic of production quality code, it must be able to handle exceptional scenario in clear cut predefined way. Whole program should never be crashed due to one single bad input or scenario.

6) Recoverable, code should be able to recover itself in case of premature closing or crash.


Also
1.    Code should be expandable. Once in production, enhancement and new requirements r bound to come. The abstract design should allow for rapid development. Developer should keep on mind when coding

2.    Writing locale independent code is also one of quality for production code. These kind of thing should be part of Resources which allows you flexibility to change the language or resource based on locale.


Read more: http://javarevisited.blogspot.com/2011/09/how-to-write-production-quality-code.html#ixzz36tJFKtkm

Monday, March 3, 2014

Concurrency in Java Swing

Concurrency in Swing

Careful use of concurrency is particularly important to the Swing programmer. A well-written Swing program uses concurrency to create a user interface that never "freezes" — the program is always responsive to user interaction, no matter what it's doing. To create a responsive program, the programmer must learn how the Swing framework employs threads.
A Swing programmer deals with the following kinds of threads:
  • Initial threads, the threads that execute initial application code.
  • The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
  • Worker threads, also known as background threads, where time-consuming background tasks are executed.
The programmer does not need to provide code that explicitly creates these threads: they are provided by the runtime or the Swing framework. The programmer's job is to utilize these threads to create a responsive, maintainable Swing program.
Like any other program running on the Java platform, a Swing program can create additional threads and thread pools, using the tools described in the Concurrency lesson. But for basic Swing programs the threads described here are sufficient.
This lesson discusses each of the three kinds of threads in turn. Worker threads require the most discussion because tasks that run on them are created using javax.swing.SwingWorker. This class has many useful features, including communication and coordination between worker thread tasks and the tasks on other threads.

Initial Threads

Every program has a set of threads where the application logic begins. In standard programs, there's only one such thread: the thread that invokes the main method of the program class. In applets the initial threads are the ones that construct the applet object and invoke its init and start methods; these actions may occur on a single thread, or on two or three different threads, depending on the Java platform implementation. In this lesson, we call these threads the initial threads.
In Swing programs, the initial threads don't have a lot to do. Their most essential job is to create a Runnable object that initializes the GUI and schedule that object for execution on the event dispatch thread. Once the GUI is created, the program is primarily driven by GUI events, each of which causes the execution of a short task on the event dispatch thread. Application code can schedule additionals tasks on the event dispatch thread (if they complete quickly, so as not to interfere with event processing) or a worker thread (for long-running tasks).
An initial thread schedules the GUI creation task by invoking javax.swing.SwingUtilities.invokeLater or javax.swing.SwingUtilities.invokeAndWait . Both of these methods take a single argument: the Runnable that defines the new task. Their only difference is indicated by their names: invokeLater simply schedules the task and returns; invokeAndWait waits for the task to finish before returning.
You can see examples of this throughout the Swing tutorial:
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        createAndShowGUI();
    }
});
In an applet, the GUI-creation task must be launched from the init method using invokeAndWait; otherwise, init may return before the GUI is created, which may cause problems for a web browser launching an applet. In any other kind of program, scheduling the GUI-creation task is usually the last thing the initial thread does, so it doesn't matter whether it uses invokeLater or invokeAndWait.
Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must run on the event dispatch thread. This restriction is discussed further in the next section.

The Event Dispatch Thread

Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors. Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

A note on thread safety: It may seem strange that such an important part of the Java platform is not thread safe. It turns out that any attempt to create a thread-safe GUI library faces some fundamental problems. For more on this issue, see the following entry in Graham Hamilton's blog: MultiThreaded toolkits: A failed dream?
It's useful to think of the code running on the event dispatch thread as a series of short tasks. Most tasks are invocations of event-handling methods, such as ActionListener.actionPerformed. Other tasks can be scheduled by application code, using invokeLater or invokeAndWait. Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive.
If you need to determine whether your code is running on the event dispatch thread, invoke javax.swing.SwingUtilities.isEventDispatchThread.

Worker Threads and SwingWorker

When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads. Each task running on a worker thread is represented by an instance of javax.swing.SwingWorker. SwingWorker itself is an abstract class; you must define a subclass in order to create a SwingWorker object; anonymous inner classes are often useful for creating very simpleSwingWorker objects.
SwingWorker provides a number of communication and control features:
  • The SwingWorker subclass can define a method, done, which is automatically invoked on the event dispatch thread when the background task is finished.
  • SwingWorker implements java.util.concurrent.Future. This interface allows the background task to provide a return value to the other thread. Other methods in this interface allow cancellation of the background task and discovering whether the background task has finished or been cancelled.
  • The background task can provide intermediate results by invoking SwingWorker.publish, causing SwingWorker.process to be invoked from the event dispatch thread.
  • The background task can define bound properties. Changes to these properties trigger events, causing event-handling methods to be invoked on the event dispatch thread.
These features are discussed in the following subsections.

Note: The javax.swing.SwingWorker class was added to the Java platform in Java SE 6. Prior to this, another class, also called SwingWorker, was widely used for some of the same purposes. The oldSwingWorker was not part of the Java platform specification, and was not provided as part of the JDK.
The new javax.swing.SwingWorker is a completely new class. Its functionality is not a strict superset of the old SwingWorker. Methods in the two classes that have the same function do not have the same names. Also, instances of the old SwingWorker class were reusable, while a new instance of javax.swing.SwingWorker is needed for each new background task.
Throughout the Java Tutorials, any mention of SwingWorker now refers to javax.swing.SwingWorker.

Worker Threads and SwingWorker

When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads. Each task running on a worker thread is represented by an instance of javax.swing.SwingWorker. SwingWorker itself is an abstract class; you must define a subclass in order to create a SwingWorker object; anonymous inner classes are often useful for creating very simpleSwingWorker objects.
SwingWorker provides a number of communication and control features:
  • The SwingWorker subclass can define a method, done, which is automatically invoked on the event dispatch thread when the background task is finished.
  • SwingWorker implements java.util.concurrent.Future. This interface allows the background task to provide a return value to the other thread. Other methods in this interface allow cancellation of the background task and discovering whether the background task has finished or been cancelled.
  • The background task can provide intermediate results by invoking SwingWorker.publish, causing SwingWorker.process to be invoked from the event dispatch thread.
  • The background task can define bound properties. Changes to these properties trigger events, causing event-handling methods to be invoked on the event dispatch thread.
These features are discussed in the following subsections.

Note: The javax.swing.SwingWorker class was added to the Java platform in Java SE 6. Prior to this, another class, also called SwingWorker, was widely used for some of the same purposes. The oldSwingWorker was not part of the Java platform specification, and was not provided as part of the JDK.
The new javax.swing.SwingWorker is a completely new class. Its functionality is not a strict superset of the old SwingWorker. Methods in the two classes that have the same function do not have the same names. Also, instances of the old SwingWorker class were reusable, while a new instance of javax.swing.SwingWorker is needed for each new background task.
Throughout the Java Tutorials, any mention of SwingWorker now refers to javax.swing.SwingWorker.

Simple Background Tasks

Let's start with a task that is very simple, but potentially time-consuming. The TumbleItem applet loads a set of graphic files used in an animation. If the graphic files are loaded from an initial thread, there may be a delay before the GUI appears. If the graphic files are loaded from the event dispatch thread, the GUI may be temporarily unresponsive.
To avoid these problems, TumbleItem creates and executes an instance of SwingWorker from its initial threads. The object's doInBackground method, executing in a worker thread, loads the images into anImageIcon array, and returns a reference to it. Then the done method, executing in the event dispatch thread, invokes get to retrieve this reference, which it assigns to an applet class field named imgs. This allowsTumbleItem to construct the GUI immediately, without waiting for the images to finish loading.
Here is the code that defines and executes the SwingWorker object.
SwingWorker worker = new SwingWorker<ImageIcon[], Void>() {
    @Override
    public ImageIcon[] doInBackground() {
        final ImageIcon[] innerImgs = new ImageIcon[nimgs];
        for (int i = 0; i < nimgs; i++) {
            innerImgs[i] = loadImage(i+1);
        }
        return innerImgs;
    }

    @Override
    public void done() {
        //Remove the "Loading images" label.
        animator.removeAll();
        loopslot = -1;
        try {
            imgs = get();
        } catch (InterruptedException ignore) {}
        catch (java.util.concurrent.ExecutionException e) {
            String why = null;
            Throwable cause = e.getCause();
            if (cause != null) {
                why = cause.getMessage();
            } else {
                why = e.getMessage();
            }
            System.err.println("Error retrieving file: " + why);
        }
    }
};

All concrete subclasses of SwingWorker implement doInBackground; implementation of done is optional.
Notice that SwingWorker is a generic class, with two type parameters. The first type parameter specifies a return type for doInBackground, and also for the get method, which is invoked by other threads to retrieve the object returned by doInBackground. SwingWorker's second type parameter specifies a type for interim results returned while the background task is still active. Since this example doesn't return interim results, Void is used as a placeholder.
You may wonder if the code that sets imgs is unnecessarily complicated. Why make doInBackground return an object and use done to retrieve it? Why not just have doInBackground set imgs directly? The problem is that the object imgs refers to is created in the worker thread and used in the event dispatch thread. When objects are shared between threads in this way, you must make sure that changes made in one thread are visible to the other. Using get guarantees this, because using get creates a happens before relationship between the code that creates imgs and the code that uses it. For more on the happens before relationship, refer to Memory Consistency Errors in the Concurrency lesson.
There are actually two ways to retrieve the object returned by doInBackground.
Be careful when invoking either overload of get from the event dispatch thread; until get returns, no GUI events are being processed, and the GUI is "frozen". Don't invoke get without arguments unless you are confident that the background task is complete or close to completion.
For more on the TumbleItem example, refer to How to Use Swing Timers in the lesson Using Other Swing Features.

Tasks that Have Interim Results

It is often useful for a background task to provide interim results while it is still working. The task can do this by invoking SwingWorker.publish. This method accepts a variable number of arguments. Each argument must be of the type specified by SwingWorker's second type parameter.
To collect results provided by publish, override SwingWorker.process This method will be invoked from the event dispatch thread. Results from multiple invocations of publish are often accumulated for a single invocation of process.
Let's look at the way the Flipper.java example uses publish to provide interim results. Click the Launch button to run Flipper using Java™ Web Start (download JDK 7 or later). Or, to compile and run the example yourself, consult the example index.
Launches the Flipper example
This program tests the fairness of java.util.Random by generating a series of random boolean values in a background task. This is equivalent to flipping a coin; hence the name Flipper. To report its results, the background task uses an object of type FlipPair
private static class FlipPair {
    private final long heads, total;
    FlipPair(long heads, long total) {
        this.heads = heads;
        this.total = total;
    }
}
The heads field is the number of times the random value has been true; the total field is the total number of random values.
The background task is represented by an instance of FlipTask:
private class FlipTask extends SwingWorker<Void, FlipPair> {
Since the task does not return a final result, it does not matter what the first type parameter is; Void is used as a placeholder. The task invokes publish after each "coin flip":
@Override
protected Void doInBackground() {
    long heads = 0;
    long total = 0;
    Random random = new Random();
    while (!isCancelled()) {
        total++;
        if (random.nextBoolean()) {
            heads++;
        }
        publish(new FlipPair(heads, total));
    }
    return null;
}
(The isCancelled method is discussed in the next section.) Because publish is invoked very frequently, a lot of FlipPair values will probably be accumulated before process is invoked in the event dispatch thread; process is only interested in the last value reported each time, using it to update the GUI:
protected void process(List<FlipPair> pairs) {
    FlipPair pair = pairs.get(pairs.size() - 1);
    headsText.setText(String.format("%d", pair.heads));
    totalText.setText(String.format("%d", pair.total));
    devText.setText(String.format("%.10g", 
            ((double) pair.heads)/((double) pair.total) - 0.5));
}
If Random is fair, the value displayed in devText should get closer and closer to 0 as Flipper runs.

Note: The setText method used in Flipper is actually "thread safe" as defined in its specification. That means that we could dispense with publish and process and set the text fields directly from the worker thread. We've chosen to ignore this fact in order to provide a simple demonstration of SwingWorker interim results.

Canceling Background Tasks

To cancel a running background task, invoke SwingWorker.cancel The task must cooperate with its own cancellation. There are two ways it can do this:
  • By terminating when it receives an interrupt. This procedures is described in Interrupts in Concurrency.
  • By invoking SwingWorker.isCancelled at short intervals. This method returns true if cancel has been invoked for this SwingWorker.
The cancel method takes a single boolean argument. If the argument is true, cancel sends the background task an interrupt. Whether the argument is true or false, invoking cancel changes the cancellation status of the object to true. This is the value returned by isCancelled. Once changed, the cancellation status cannot be changed back.
The Flipper example from the previous section uses the status-only idiom. The main loop in doInBackground exits when isCancelled returns true. This will occur when the user clicks the "Cancel" button, triggering code that invokes cancel with an argument of false.
The status-only approach makes sense for Flipper because its implementation of SwingWorker.doInBackground does not include any code that might throw InterruptedException. To respond to an interrupt, the background task would have to invoke Thread.isInterrupted at short intervals. It's just as easy to use SwingWorker.isCancelled for the same purpose

Note: If get is invoked on a SwingWorker object after its background task has been cancelled, java.util.concurrent.CancellationException is thrown.

Bound Properties and Status Methods

SwingWorker supports bound properties, which are useful for communicating with other threads. Two bound properties are predefined: progress and state. As with all bound properties, progress and statecan be used to trigger event-handling tasks on the event dispatch thread.
By implementing a property change listener, a program can track changes to progress, state, and other bound properties. For more information, refer to How to Write a Property Change Listener in Writing Event Listeners.

The progress Bound Variable

The progress bound variable is an int value that can range from 0 to 100. It has a predefined setter method (the protected SwingWorker.setProgress) and a predefined getter method (the publicSwingWorker.getProgress).
The ProgressBarDemo example uses progress to update a ProgressBar control from a background task. For a detailed discussion of this example, refer to How to Use Progress Bars in Using Swing Components.

The state Bound Variable

The state bound variable indicates where the SwingWorker object is in its lifecycle. The bound variable contains an enumeration value of type SwingWorker.StateValue. Possible values are:
PENDING
The state during the period from the construction of the object until just before doInBackground is invoked.
STARTED
The state during the period from shortly before doInBackground is invoked until shortly before done is invoked.
DONE
The state for the remainder of the existence of the object.
The current value of the state bound variable is returned by SwingWorker.getState.

Status Methods

Two methods, part of the Future interface, also report on the status of the background task. As we saw in Canceling Background Tasks, isCancelled returns true if the task has been canceled. In addition,isDone returns true if the task has finished, either normally, or by being cancelled.

Questions

  1. For each of the following tasks, specify which thread it should be executed in and why.
  2. One set of threads is not used for any of the tasks mentioned in the previous question. Name this thread and explain why its applications are so limited.
  3. SwingWorker has two type parameters. Explain how these type parameters are used, and why it often doesn't matter what they are.

Sunday, March 2, 2014

MySql cheatsheet


Connecting to and Disconnecting from the Server


To connect to the server, you will usually need to provide a MySQL user name when you invoke mysql and, most likely, a password. If the server runs on a machine other than the one where you log in, you will also need to specify a host name. Contact your administrator to find out what connection parameters you should use to connect (that is, what host, user name, and password to use). Once you know the proper parameters, you should be able to connect like this:
shell> mysql -h host -u user -p
Enter password: ********
host and user represent the host name where your MySQL server is running and the user name of your MySQL account. Substitute appropriate values for your setup. The ******** represents your password; enter it whenmysql displays the Enter password: prompt.
If that works, you should see some introductory information followed by a mysql> prompt:
shell> mysql -h host -u user -p
Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 25338 to server version: 5.0.96-standard

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>
The mysql> prompt tells you that mysql is ready for you to enter commands.
If you are logging in on the same machine that MySQL is running on, you can omit the host, and simply use the following:
shell> mysql -u user -p
If, when you attempt to log in, you get an error message such as ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2), it means that the MySQL server daemon (Unix) or service (Windows) is not running. Consult the administrator or see the section of Chapter 2, Installing and Upgrading MySQL that is appropriate to your operating system.
For help with other problems often encountered when trying to log in, see Section C.5.2, “Common Errors When Using MySQL Programs”.
Some MySQL installations permit users to connect as the anonymous (unnamed) user to the server running on the local host. If this is the case on your machine, you should be able to connect to that server by invoking mysqlwithout any options:
shell> mysql
After you have connected successfully, you can disconnect any time by typing QUIT (or \q) at the mysql> prompt:
mysql> QUIT
Bye
On Unix, you can also disconnect by pressing Control+D.
Most examples in the following sections assume that you are connected to the server. They indicate this by themysql> promp

Creating and Using a Database

If the administrator creates your database for you when setting up your permissions, you can begin using it. Otherwise, you need to create it yourself:
mysql> CREATE DATABASE menagerie;

Creating a database does not select it for use; you must do that explicitly. To make menagerie the current database, use this command:

mysql> USE menagerie
Database changed

Creating a Table

Creating the database is the easy part, but at this point it is empty, as SHOW TABLES tells you:
mysql> SHOW TABLES;
Empty set (0.00 sec)

Use a CREATE TABLE statement to specify the layout of your table:
mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20),
    -> species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);

Once you have created a table, SHOW TABLES should produce some output:
mysql> SHOW TABLES;
+---------------------+
| Tables in menagerie |
+---------------------+
| pet                 |
+---------------------+

To verify that your table was created the way you expected, use a DESCRIBE statement:
mysql> DESCRIBE pet;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name    | varchar(20) | YES  |     | NULL    |       |
| owner   | varchar(20) | YES  |     | NULL    |       |
| species | varchar(20) | YES  |     | NULL    |       |
| sex     | char(1)     | YES  |     | NULL    |       |
| birth   | date        | YES  |     | NULL    |       |
| death   | date        | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
You can use DESCRIBE any time, for example, if you forget the names of the columns in your table or what types they have.

Loading Data into a Table
After creating your table, you need to populate it. The LOAD DATA and INSERT statements are useful for this.
Suppose that your pet records can be described as shown here. (Observe that MySQL expects dates in 'YYYY-MM-DD' format; this may be different from what you are used to.)
nameownerspeciessexbirthdeath
FluffyHaroldcatf1993-02-04
ClawsGwencatm1994-03-17
BuffyHarolddogf1989-05-13
FangBennydogm1990-08-27
BowserDianedogm1979-08-311995-07-29
ChirpyGwenbirdf1998-09-11
WhistlerGwenbird1997-12-09
SlimBennysnakem1996-04-29
Because you are beginning with an empty table, an easy way to populate it is to create a text file containing a row for each of your animals, then load the contents of the file into the table with a single statement.
You could create a text file pet.txt containing one record per line, with values separated by tabs, and given in the order in which the columns were listed in the CREATE TABLE statement. For missing values (such as unknown sexes or death dates for animals that are still living), you can use NULL values. To represent these in your text file, use \N (backslash, capital-N). For example, the record for Whistler the bird would look like this (where the whitespace between values is a single tab character):
Whistler        Gwen    bird    \N      1997-12-09      \N
To load the text file pet.txt into the pet table, use this statement:
mysql> LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet;
If you created the file on Windows with an editor that uses \r\n as a line terminator, you should use this statement instead:
mysql> LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet
    -> LINES TERMINATED BY '\r\n';
(On an Apple machine running OS X, you would likely want to use LINES TERMINATED BY '\r'.)
You can specify the column value separator and end of line marker explicitly in the LOAD DATA statement if you wish, but the defaults are tab and linefeed. These are sufficient for the statement to read the file pet.txtproperly.
If the statement fails, it is likely that your MySQL installation does not have local file capability enabled by default. See Section 6.1.6, “Security Issues with LOAD DATA LOCAL”, for information on how to change this.
When you want to add new records one at a time, the INSERT statement is useful. In its simplest form, you supply values for each column, in the order in which the columns were listed in the CREATE TABLE statement. Suppose that Diane gets a new hamster named “Puffball.” You could add a new record using an INSERT statement like this:
mysql> INSERT INTO pet
    -> VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL);
String and date values are specified as quoted strings here. Also, with INSERT, you can insert NULL directly to represent a missing value. You do not use \N like you do with LOAD DATA.
From this example, you should be able to see that there would be a lot more typing involved to load your records initially using several INSERT statements rather than a single LOAD DATA statement.






Delete database
> drop database feedback