Thursday, December 6

Applets in Java


Where Do Applets and Classes Come from?
When a web browser sees an applet tag and decides to download and play the applet,
it starts a long chain of events. Let's say your browser sees the following applet tag:

<APPLET codebase="http://metalab.unc.edu/javafaq/classes"
code="Animation.class" width="200" height="100" >
<PARAM NAME = “FRAMErATE”   VALUE = “10”>
</APPLET>

1.      The web browser sets aside a rectangular area on the page 200 pixels wide and
100 pixels high. In most web browsers, this area has a fixed size and cannot be
modified once created. The appletviewer in the JDK is a notable exception.
2.      The browser opens a connection to the server specified in the codebase parameter, using port 80 unless another port is specified in the codebase URL. If there's no codebase parameter, then the browser connects to the same server that served the HTML page.
3.      The browser requests the .class file from the web server as it requests any other file. If a codebase is present, it is prefixed to the requested filename. Otherwise, the document base (the directory that contains the HTML page) is used. For example:
GET /javafaq/classes/Animation.class HTTP 1.0

4.      The server responds by sending a MIME header followed by a blank line (\r\n) followed by the binary data in the .class file. A properly configured server sends .class files with MIME type application/octet-stream. For example:
HTTP 1.0 200 OK
Date: Mon, 10 Jun 1999 17:11:43 GMT
Server: Apache/1.2.8
Content-type: application/octet-stream
Content-length: 2782
Last-modified: Fri, 08 Sep 1998 21:53:55 GMT
5.      The web browser receives the data and stores it in a byte array. The byte code verifier goes over the byte codes that have been received to make sure they don't do anything forbidden, such as converting an integer into a pointer.
6.      If the byte code verifier is satisfied with the bytes that were downloaded, then the raw data is converted into a Java class using the defineClass( ) and loadClass( ) methods of the current ClassLoader object.
7.      The web browser instantiates the Animation class using its noargs constructor.
8.      The web browser invokes the init( ) method of Animation.
9.       The web browser invokes the start( ) method of Animation.

10.  If the Animation class references another class, the Java interpreter first searches for
the new class in the user's CLASSPATH. If the class is found in the user's CLASSPATH,
then it is created from the .class file on the user's hard drive. Otherwise the web
browser goes back to the site from which this class came and downloads the .class file for the new class. The same procedure is followed for the new class and any other
class that is downloaded from the Net. If the new class cannot be found, a
ClassNotFoundException is thrown



Who Can an Applet Talk to and What Can It Say?

1.      Applets cannot access arbitrary addresses in memory. Unlike the other restrictions in the list, which are enforced by the browser's SecurityManager instance, this restriction is a property of the Java language itself and the byte code verifier.
2.      Applets cannot access the local filesystem in any way. They cannot read from or write to the local filesystem nor can they find out any information about files. Therefore, they cannot find out whether a file exists or what its modification date may be.
3.      Applets cannot launch other programs on the client. In other words, they
cannot call System.exec( ) or Runtime.exec( ).
4.      Applets cannot load native libraries or define native method calls.
5.      Applets are not allowed to use System.getProperty( ) in a way that reveals
information about the user or the user's machine, such as a username or home
directory. They may use System.getProperty( ) to find out what version of
Java is in use.
6.       Applets may not define any system properties.
7.      In Java 1.1 and later, applets may not create or manipulate any Thread or
ThreadGroup that is not in the applet's own ThreadGroup. They may do this
in Java 1.0.
8.       Applets cannot define or use a new instance of ClassLoader, SecurityManager, ContentHandlerFactory, SocketImplFactory, or URLStreamHandlerFactory. They must use the ones already in place.

9.      An applet can only open network connections to the host from which the applet itself was downloaded.
10.  An applet cannot listen on ports below 1,024. (Internet Explorer 5.0 doesn't
allow applets to listen on any ports.)
11.  Even if an applet can listen on a port, it can accept incoming connections only
from the host from which the applet itself was downloaded.

Thread Scheduling And Socket


1.      Thread Scheduling
There are two kinds of thread scheduling, preemptive and cooperative.
  • A preemptive thread scheduler determines when a thread has had its fair share of CPU time, pauses that thread, and then hands off control of the CPU to a different thread.
  • A cooperative thread scheduler waits for the running thread to pause itself before handing off control of the CPU to a different thread.
  • A virtual machine that uses cooperative thread scheduling is much more susceptible to thread starvation than a virtual machine that uses preemptive thread scheduling.
2.      Synchronization, wait(), notify(), notifyAll()
Monitor objects maintain a list of all threads waiting to enter the monitor object to execute synchronized methods. A thread is inserted in the list and waits for the object if that thread calls a synchronized method of the object while another thread is already executing in a synchronized method of that object. A thread also is inserted in the list if the thread calls wait while operating inside the object. However, it is important to distinguish between waiting threads that blocked because the monitor was busy and threads that explicitly called wait inside the monitor. Upon completion of a synchronized method, outside threads that blocked because the monitor was busy can proceed to enter the object. Threads that explicitly invoked wait can proceed only when notified via a call by another thread to notify or notifyAll. When it is acceptable for a waiting thread to proceed, the scheduler selects the thread with the highest priority.


A socket is a connection between two hosts. It can perform seven basic operations:

·         Connect to a remote machine
·         Send data
·         Receive data
·         Close a connection
·         Bind to a port
·         Listen for incoming data
·         Accept connections from remote machines on the bound port

Client Sockets
·         The program creates a new socket with a Socket( ) constructor.
·         The socket attempts to connect to the remote host.
·         Once the connection is established, the local and remote hosts get input and output streams from the socket and use those streams to send data to each other.
·         This connection is full-duplex; both hosts can send and receive data simultaneously.
·         What the data means depends on the protocol; different commands are sent to an FTP server than to an HTTP server. There will normally be some agreed-upon hand-shaking followed by the transmission of data from one to the other.
·         When the transmission of data is complete, one or both sides close the connection. Some protocols, such as HTTP 1.0, require the connection to be closed after each request is serviced. Others, such as FTP, allow multiple requests to be processed in a single connection.

Threads


1.      Threads are subtasks in a program that can be in execution concurrently.
2.      The concurrency that computers perform today is normally implemented as operating system primitives” available only to highly experienced “systems programmers.”
3.      Java makes concurrency primitives available to the programmer.
4.      Subclass the Thread class and override its run( ) method.
5.      implement the Runnable interface and pass the Runnable object to the Thread constructor. Runnable has one method run().
6.      Signature of function: public void run( )
7.      run method may invoke other methods; it may construct other objects; it may even spawn other threads. The thread starts here and it stops here. When the run( ) method completes, the thread dies.
8.      the run( ) method is to a thread what the main( )method is to a traditional nonthreaded program.
9.      A single-threaded program exits when the main( ) method returns.
10.  A multithreaded program exits when both the main( ) method and the run( ) methods of all nondaemon threads return. (Daemon threads perform background tasks such as garbage collection and don't prevent the virtual machine from exiting.)
11.  Extending Thread Class
class A extends Thread
{
public static void main (String[] args)
{
Thread t = new A();
t.start( );
}
public void run()
{
//details
}
}

12.  Implementing Runnable:

class A implements Runnable
{
public static void main (String[] args)
{
A a = new A();
Thread t = new Thread(a);
t.start( );
}
public void run()
{
//details
}
}

13.  Passing Information to Thread.
14.  Returning Information from Thread.
15.  Avoid Race Condition.
16.  A thread specified as daemon will cease execution when the thread that created it ends. Syntax: threadName.setDaemon(true);
17.  A thread that is not daemon is called a user thread.
18.  Synchronized methods
public synchronized void writeEntry(String message)
19.  Every object that has synchronized methods has a monitor. The monitor lets only one thread at a time execute a synchronized method on the object.
20.  Only one synchronized instance method for an object can execute at any given time. Only one synchronized static method for a class can execute at one time.

21.  Synchronized Blocks
A code block can be declared as a synchronized on an object. Only one synchronized code block for an object can execute at any given time.
synchronized (System.out)
{
System.out.print(input + ": ");
for (int i = 0; i < digest.length; i++)
{
System.out.print(digest[i] + " ");
}
System.out.println( );
}
22.  Thread Scheduling
  • All important threads get at least some time to run and that the more important threads get more time.
  • Threads should execute in a reasonable order.(e.g. not in series)
  • Thread should not suffer through starvation.
23.  Thread Priority
  • Priority is specified as an integer ranging from 1(lowest) to 10(highest).
  • When multiple threads are able to run, generally the VM will run only the highest-priority thread,
  • public final void setPriority(int newPriority)
  • public final int getPriority( )

24.  Suspension of Thread
There are 10 ways a thread can pause in favor of other threads or indicate that it is ready to pause. These are:
  • It can block on I/O.
  • It can block on a synchronized object.
A thread can wait on an object it has locked. While waiting, it releases the lock on the object and pauses until it is notified by some other thread. Another thread changes the object in some way, notifies the thread waiting on that object, and then continues.
  • It can yield.
  • It can go to sleep.
A thread that goes to sleep does hold onto all the locks it's grabbed. Consequently, other threads that need the same locks will be blocked even if the CPU is available.

  • It can join another thread.
  • It can wait on an object.
  • It can finish.
There's a nontrivial amount of overhead for the virtual machine in setting up and tearing down threads.
  • It can be preempted by a higher-priority thread.
  • It can be suspended.
It can stop.