Java Thread 2nd Edition O'REILLY


Java Threads, Second Edition

By Scott Oaks and Henry Wong




Description :
Revised and expanded to cover Java 2, Java Threads shows you how to take full advantage of Java's thread facilities: where to use threads to increase efficiency, how to use them effectively, and how to avoid common mistakes. It thoroughly covers the Thread and ThreadGroup classes, the Runnable interface, and the language's synchronized operator. The book pays special attention to threading issues with Swing, as well as problems like deadlock, race condition, and starvation to help you write code without hidden bugs.

Threads aren't a new idea: many operating systems and languages support them. But despite widespread support, threads tend to be something that everyone talks about, but few use. Programming with threads has a reputation for being tricky and nonportable. Not so with Java. Java's thread facilities are easy to use, and--like everything else in Java--are completely portable between platforms. And that's a good thing, because it's impossible to write anything but the simplest applet without encountering threads. If you want to work with Java, you have to learn about threads. This new edition shows you how to take full advantage of Java's thread facilities: where to use threads to increase efficiency, how to use them effectively, and how to avoid common mistakes. Java Threads discusses problems like deadlock, race condition, and starvation in detail, helping you to write code without hidden bugs. It brings you up to date with the latest changes in the thread interface for JDK 1.2. The book offers a thorough discussion of the Thread and ThreadGroup classes, the Runnable interface, the language's synchronized operator. It explains thread scheduling ends by developing a CPUSchedule class, showing you how to implement your own scheduling policy. In addition, Java Threads shows you how to extend Java's thread primitives. Other extended examples include classes that implement reader/writer locks, general locks, locks at arbitrary scope, and asynchronous I/O. This edition also adds extensive examples on thread pools, advanced synchronization technique, like condition variables, barriers, and daemon locks. It shows how to work with classes that are not thread safe, and pays special attention to threading issues with Swing. A new chapter shows you how to write parallel code for multiprocessor machines. In short, Java Threads covers everything you need to know about threads, from the simplest animation applet to the most complex applications. If you plan to do any serious work in Java, you will find this book invaluable. Examples available online. Covers Java 2.

Media reviews

"If you are new to Java programming and have yet to conquer threads, Java Threads is an excellent resource. You'll get a look into the basics of Java threading, and learn the techniques necessary to get your programs to function properly in a multithreaded world. Five stars" --John Zukowski, Java World, 03/2001

"This is a good book, and certainly, if you're using threads in Java non-trivially then you should have this book. Otherwise, borrow a copy and read the first half to make yourself aware of the threading issues in Java. Even better, think how your code affects others; the section on mixing threads with thread unsafe classes should make you aware of the wider issues surrounding your code, and hopefully, you'll produce well behaved classes that will be easily multi- threaded if the need arises? Do you use the collections? Think hard..."1999 --Steve Cornish, C Vu, September 1999

"A very useful well-written reference suitable for Java systems developers and as a second level text for students on computing science and IT oriented courses. Highly recommended!" --Brian Bamer, C Vu January 1998



January 1999
Pages: 336
ISBN 10: 1-56592-418-5 | ISBN 13: 9781565924185

Click Here to Download
Read more

Java™ Extreme Programming Cookbook



Brimming with over 100 "recipes" for getting down to business and actually doing XP, the Java Extreme Programming. Cookbook doesn't try to "sell" you on XP; it succinctly documents the most important features of popular open source tools for XP in Java-- including Ant, Junit, HttpUnit, Cactus, Tomcat, XDoclet-- and then digs right in,
providing recipes for implementing the tools in real-world environments.

Java™ Extreme Programming Cookbook
By Eric M. Burke, Brian M. Coyner
Publisher : O'Reilly
Pub Date : March 2003
ISBN : 0-596-00387-0
Pages : 288

Click here to download
Read more

TooltipsList Demo


import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.UIManager;

public class tiplist extends JFrame {

public tiplist() {
super("ToolTip Example");

String[][] strs = { { "Item1", "HDD" },
{ "Item2", "Monitor" }, { "Item3", "Ram" },
{ "Item4", "DVD-Writer" }, { "Item5", "Microprocessor" } };

JList list = new JList(createItems(strs)) {
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 <>
ToolTipItem item = (ToolTipItem) getModel().getElementAt(
index);
return item.getToolTipText();
} else {
//return super.getToolTipText();
return null;
}
}
};
list.setToolTipText("");

getContentPane().add(new JScrollPane(list), BorderLayout.CENTER);
}

Object[] createItems(String[][] strs) {
ToolTipItem[] items = new ToolTipItem[strs.length];
for (int i = 0; i <>
items[i] = new ToolTipItem(strs[i][0], strs[i][1]);
}
return items;
}

class ToolTipItem {
String obj;

String toolTipText;

public ToolTipItem(String obj, String text) {
this.obj = obj;
this.toolTipText = text;
}

public String getToolTipText() {
return toolTipText;
}

public String toString() {
return obj;
}
}

public static void main(String args[]) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception evt) {}

tiplist frame = new tiplist();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setSize(140, 150);
frame.setVisible(true);
}
}
Read more

How to run simple JSP program


First you have to put your JSP file into the container's folder. The folder must contains a sub folder named "WEB-INF".

For an example, if we use Apache Tomcat (assume Tomcat installed to C:\Tomcat directory), you have to put your jsp file into a subfolder of C:\Tomcat\webapp folder.

Assume, your jsp file is "index.jsp"; in this case, you have to put it as:
C:\Tomcat\webapp\MyName\index.jsp

And, there should be another sub folder named "WEB-INF" as:
C:\Tomcat\webapp\MyName\WEB-INF
(However, this folder can be empty)

After that, you have to restart your web server (this is vendor specific), and you can see the output via the browser.

By default, many J2EE web servers uses 8080 port for the client access. In this case, you can see the output on your local machine by typing the following address on your browser's address bar:

http://localhost:8080/MyName

--------------------------------------...


Sample program for index.jsp
======================



<% String myName="krish"; out.println(myName); %>
<%=myName%>




The output should be:
krish krish

More info

Under the Tomcat root directory there will be a sub-directory named web-apps, all web applications running on this Tomcat server will reside there. Each web application will have it's own sub-directory under web-apps, so you could create a directory for your web application under the web-apps directory like so /web-apps/. JSP pages can be placed insisde the directory you have created or in other sub-directories you might like to create, however please note that for each new sub-directory you place your JSP files in the URL to access them will need to include each directory.

Inside the directory you created there needs to be another directory named WEB-INF, this directory will contain the web.xml file which contains configuration information for your web application such as the welcome file for your application, all servlet mappings, filters, etc...

Under the WEB-INF directory you can create another directory named classes, all your java classes used in your web application should be placed in here, in a tree structure that resembles their packages, for example: if you have a class named MyClass whose package is com.xyz then the class should be placed in /web-apps//WEB-INF/classes/com/xyz/MyClass.class. Another alternative to handling classes in this way is to package them all in a jar file, the jar file can be placed in a directory named lib also under the WEB-INF directory, for example: say you have a jar file named myLibrary.jar, it can be placed in /web-apps//WEB-INF/lib/myLibrary.jar. By placing classes and jar files in these directories Tomcat ensures they are on the CLASSPATH when you run your application.

An alternative to repeating this procedure each time you want to deploy some JSP pages to your Tomcat server is to simply create a WAR file and use the Tomcat manager (which can be accessed through a browser window) to deploy the WAR file to the server


Read more

Create your tray icon



import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test {
static Image image = Toolkit.getDefaultToolkit().getImage("c:/tray.gif");

static TrayIcon trayIcon = new TrayIcon(image, "Tester2");

public static void main(String[] a) throws Exception {
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();

trayIcon.setImageAutoSize(true);
trayIcon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("In here");
trayIcon.displayMessage("Tester!", "Some action performed", TrayIcon.MessageType.INFO);
}
});

try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println("TrayIcon could not be added.");
}
}
}
}

Read more

Simple http server


import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HttpServerDemo {
public static void main(String[] args) throws IOException {
InetSocketAddress addr = new InetSocketAddress(8080);
HttpServer server = HttpServer.create(addr, 0);

server.createContext("/", new MyHandler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port 8080" );
}
}

class MyHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")) {
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, 0);

OutputStream responseBody = exchange.getResponseBody();
Headers requestHeaders = exchange.getRequestHeaders();
Set keySet = requestHeaders.keySet();
Iterator iter = keySet.iterator();
while (iter.hasNext()) {
String key = iter.next();
List values = requestHeaders.get(key);
String s = key + " = " + values.toString() + "\n";
responseBody.write(s.getBytes());
}
responseBody.close();
}
}
}

Read more

Java Dsktop Helper


import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class DesktopDemo {
static Desktop desktop;
public static void main(String[] args) {

if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
} else {
System.out.println("Desktop class is not supported");
System.exit(1);
}
JMenuItem openItem = new JMenuItem("Open");
JMenuItem editItem = new JMenuItem("Edit");
JMenuItem printItem = new JMenuItem("Print");
JMenuItem browseToItem = new JMenuItem("Go to java-tek.blogspot.com");
JMenuItem mailToItem = new JMenuItem("Email to neokristar@gmail.com");
JMenu fileMenu = new JMenu("File");
JMenu mailMenu = new JMenu("Email");
JMenu browseMenu = new JMenu("Browser");

openItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
try {
desktop.open(chooser.getSelectedFile().getAbsoluteFile());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
fileMenu.add(openItem);

editItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
try {
desktop.edit(chooser.getSelectedFile().getAbsoluteFile());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
fileMenu.add(editItem);

printItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
try {
desktop.print(chooser.getSelectedFile().getAbsoluteFile());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
fileMenu.add(printItem);

browseToItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
URI browseURI = new URI("java-tek.blogspot.com");
desktop.browse(browseURI);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
});
browseMenu.add(browseToItem);

mailToItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
URI mailURI = new URI("mailto:support@java.com");
desktop.mail(mailURI);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
});
mailMenu.add(mailToItem);

JMenuBar jMenuBar = new JMenuBar();
jMenuBar.add(fileMenu);
jMenuBar.add(browseMenu);
jMenuBar.add(mailMenu);

JFrame frame = new JFrame();
frame.setTitle("Desktop Helper Applications");
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(jMenuBar);
frame.setVisible(true);

}
}

Read more

Open word file with Java program


import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

public class Test {
public static void main(String[] a) {
try {
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}

desktop.open(new File("c:\\a.doc"));
} catch (IOException ioe) {
ioe.printStackTrace();
}

}
}

Read more

Printing a file using system default printer


import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

public class Test {
public static void main(String[] a) {
try {
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}

desktop.print(new File("c:\\a.txt"));
} catch (IOException ioe) {
ioe.printStackTrace();
}

}
}

Read more

List all drives and their space info in your computer


import java.io.File;

public class SpaceChecker {
public static void main(String[] args) {
File[] roots = File.listRoots();

for (int i = 0; i <>) {
System.out.println(roots[i]);
System.out.println(
"Free space = " + roots[i].getFreeSpace());
System.out.println(
"Usable space = " + roots[i].getUsableSpace());
System.out.println(
"Total space = " + roots[i].getTotalSpace());
System.out.println();
}
}
}

Read more

Java How to Program (4th Edition) - Dietel



An introduction to the Java 2 Platform, Standard edition, using the author's LIVE-CODE training methods. Covers data structures/collections, exceptions, multithreading, files, streams, serialization, and more. Provides screen captures and Internet resources

The authoritative DEITEL™ LIVE-CODE™ introduction to programming with the Java™ 2 Platform, Standard Edition (J2SE)

Java™ has revolutionized software development with multimedia-intensive, platform-independent, object-oriented code for conventional, Internet-, Intranet- and Extranet-based applications and applets. This exciting new Fourth Edition of the world's best-selling Java textbook now has a companion volume—Advanced Java 2 Platform How to Program—which focuses on the Java 2 Platform, Enterprise Edition (J2EE), presents advanced J2SE features and introduces the Java 2 Platform, Micro Edition (J2ME).

Dr. Harvey M. Deitel and Paul J. Deitel are the founders of Deitel & Associates, Inc., the internationally recognized corporate training and content-creation organization specializing in Java, C++, C, Visual C#™, Visual Basic®, Visual C++®, .NET, XML™, Python, Perl, Internet, Web and object technologies. The Deitels are also the authors of the world's #1 C++ textbook—C++ How to Program, 3/e—and many other best sellers.

In Java How to Program, Fourth Edition the Deitels introduce the fundamentals of object-oriented programming in Java. The 4th edition includes an optional 180-page case study that introduces object-oriented design with the UML.

Product Details

  • Paperback: 1546 pages
  • Publisher: Prentice Hall; 4 edition (August 8, 2001)
  • Language: English
  • ISBN-10: 0130341517
  • ISBN-13: 978-0130341518
  • Product Dimensions: 8.8 x 7.2 x 1.6 inches
  • Shipping Weight: 4.2 pounds
Click here to download


Read more

Sun Microsystems and Oracle have confirmed that the two companies will merge






Oracle is buying Sun Microsystems in deal valued at $7.4 billion (£5.08 billion).
The two industry giants have entered into a definitive agreement in which Oracle will acquire Sun stock at $9.50 (£6.50) a share.

In an announcement to the press, Larry Ellison, Oracle’s chief executive, predicted that through the acquisition, Sun could experience $1.5 billion in annual growth.

He said: “Solaris and Java have been instrumental in Oracle’s decision to buy Sun. Oracle can increase investment in Java for its middleware and Solaris is by far the best UNIX technology available with more Oracle databases running on this than any other system.”

The focus for the future is on building an integrated system, using the soon-to-be-created joint expertise and providing what Ellison called “an integrated system from database to disk.”

Sun’s chairman, Scott McNealy, added: “Sun and Oracle have been partners for over 20 years but today marks the next big step. This is truly momentous for the industry as we will be the only totally integrated system available and the largest supplier of Open software.”

“There is no question in my mind that this deal redraws the boundaries in the industry.”
Previously, it was IBM who was the favourite to buy Sun, but reports claim that the company had lost interest.

Read more

The Complete Reference Java 2


The Complete Reference Java 2
By Herb Schildt



Java 2: The Complete Reference blends the expertise found in Java 1: The
Complete Reference with Java 2 topics such as "servlets" and "Swing." As
before, there's help with Java Beans and migrating from C++ to Java. A
special chapter gives networking basics and breaks out networking-related
classes. This book helps you master techniques by doing as well as reading.
Projects include a multi-player word game with attention paid to network
security. The book is updated where appropriate throughout, and the rhythm
of text, code, tables, and illustrations is superb. It's a valuable resource for the
developer who is elbow-deep in demanding projects.

Product Details

  • Paperback: 1077 pages
  • Publisher: Osborne/McGraw-Hill; 4th edition (December 12, 2000)
  • Language: English
  • ISBN-10: 0072130849
  • ISBN-13: 978-0072130843
  • Product Dimensions: 9 x 7.4 x 2.1 inches
  • Shipping Weight: 4.3 pounds
Click Here to Download
Read more