View RSS Feed

My Java Tips

ThreadLocal

Rate this Entry
by , 10-29-2011 at 07:36 PM (777 Views)
I will present an example that shows how to start, stop, suspend, and resume threads.


It uses the Runnable interface because it extends from Applet class and multiple inheritance is not allowed. This example uses a thread that counts and prints a string every second. The thread starts when the applet is initialized. It continues to run until the user leaves the page. If the user returns to the page (and all is well), the thread continues from where it left off. This allows applets to retain their states while the user is away.

Java Code:
import java.lang.Thread;
import java.applet.Applet;

public class InfiniteThreadExample extends Applet implements Runnable
{
  Thread myThread;

  public void init()
    {
      System.out.println("in init() -- starting thread.");
      myThread= new Thread(this);
      myThread.start();
    }

  public void start()
    {
      System.out.println("in start() -- resuming thread.");
      myThread.resume();
    }

  public void stop()
    {
      System.out.println("in stop() -- suspending thread.");
      myThread.suspend();
    }

  public void destroy()
    {
      System.out.println("in destroy() -- stoping thread.");
      myThread.resume();
      myThread.stop();
    }

  public void run()
    {
      int i=0;
      for(;;)
        {
          i++;
          System.out.println("At " + i + " and counting!");
          try {myThread.sleep(1000);}
          catch (InterruptedException e ) {}
        }
    }
}
Do note that each thread will hold an implicit reference to its copy of a thread-local variable. It will keep holding as long as the thread is alive and the ThreadLocal instance is accessible; When a thread is killed, all of its copies of thread-local instances are subject to garbage collection.


Methods provided by this class:

Java Code:
Object get()
protected  Object initialValue()
void set(Object value)
Use get() to get the value in the current thread's copy of this thread-local variable.
Use set(...) to set the current thread's copy of this thread-local variable to the specified value.
initialValue() simply returns the current thread's initial value for this thread-local variable.

I hope you will use this in your code where needed and will find this really useful.

Submit "ThreadLocal" to Facebook Submit "ThreadLocal" to Digg Submit "ThreadLocal" to del.icio.us Submit "ThreadLocal" to StumbleUpon Submit "ThreadLocal" to Google

Tags: None Add / Edit Tags
Categories
Glassfish , Java SE

Comments