DZone Forums
Go Back   DZone Forums > Community > Languages & Frameworks > Java
Reload this Page IllegalThreadStateException in applet using SwingWorker?
Notices
Reply
 
LinkBack Thread Tools Display Modes
  (#1 (permalink)) Old
Member
 
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Sep 2008
Lightbulb IllegalThreadStateException in applet using SwingWorker? - 09-11-2008, 02:03 AM

hi,
i have a problem while reloading the applet with SwingWorker. it works fine in first time, if i reload with the same browser means the Applet window is opened but if i clicking the Download Button means it shows an Exception like "illegalThreadStateException" and it wont perform the copying files.

i have included my code :

Code:
jsp code:
 
<html> 
<body>
<%
String projid="P0001396";
%>
<jsp:plugin archive="archivedownload.jar" type="applet" code="archiveapplet.class" codebase="/archivedownload">
<jsp:params>
<jsp:param name="projid" value="<%=projid%>"/> 
</jsp:params>
<jsp:fallback>
<p> unable to load Plugin </p>
</jsp:fallback>
</jsp:plugin>
</body>
</html>
 
 
this is my applet code:
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
import java.io.*; 
 
public class archiveapplet extends Applet
{
  public boolean status=false;
  archivedownload arch;
  
  public void init()
  {
    setBackground(Color.red);
  }
 
  public void start()
  {
    if (arch==null) {
      arch = new archivedownload("");
    } else {
      arch.setVisible(true);
    }
    status=true;
  }
 
  public void stop()
  {
    System.out.println("stop()");
    status=false;
    arch.setVisible(false);
    try
    {
      Thread.sleep(1);
    }
    catch (Exception ee)
    {
      System.out.println("The Exception is ====>"+ee);
    }
  }
 
  public void destroy(){
    System.out.println("destroy()");
    arch = null;
    System.gc();
  }
 
  public static void main(String[] args)
  {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    try
    {
        UIManager.setLookAndFeel(
        "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    }
    catch (Exception ex)
    {
      System.out.println("Failed loading L&F: ");
      System.out.println(ex);
    }
    new archivedownload("");
  }
}
 
class archivedownload extends JFrame
{
  private JButton Exit;
  private JButton download;
  File f1;
  File f2;
 
  public archivedownload(String val)
  {
    super();
    initializeComponent();
    this.setVisible(true);
  }
 
  private void initializeComponent()
  {
    Exit = new JButton();
	download = new JButton();
    JPanel contentPane = (JPanel)this.getContentPane();
    Exit.setText("Exit");
    Exit.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
      {
        Exit_actionPerformed(e);
      }
 
    });
 
   download.setText("Download");
    download.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
      {
        download_actionPerformed(e);
      }
 
    });
 
    contentPane.setLayout(null);
    addComponent(contentPane, Exit, 169,92,83,28);
    addComponent(contentPane, download, 48,92,83,28);
    this.setTitle("archivedownload - extends JFrame");
    this.setLocation(new Point(0, 0));
    this.setSize(new Dimension(420, 227));
  }
 
  private void addComponent(
    Container container,
    Component c,
    int x,
    int y,
    int width,
    int height)
  {
    c.setBounds(x,y,width,height);
    container.add(c);
  }
 
 
  private void Exit_actionPerformed(ActionEvent e)
  {
    this.dispose(); 
  }
 
 private void download_actionPerformed(ActionEvent e)
  {
	 try
	 {
    System.out.println("inside Folder copy");
    
	f1 = new File("c"+":/"+"fms/");
	f2= new File("d"+":/"+"fms/"); 
 
		SwingWorker sw = new SwingWorker() {
        protected Object doInBackground() throws Exception {
	
		copyDirectory(f1,f2);  // this is for copy files from C: fms(folder) to D: (fms) 			
		System.out.println("Folder Copied ");
		return null;
		}};
 
		sw.execute();
		if(sw.isDone()){
		sw = null;
		}
 
	 }
	 catch (Exception ee)
	 {
		 System.out.println("The Exception is -->"+ee);
	 }
 
  }
public void copyDirectory(File srcDir, File dstDir) throws IOException {
		if (srcDir.isDirectory()) {
            if (!dstDir.exists()) {
                dstDir.mkdir();
            }    
            String[] children = srcDir.list();
            for (int i=0; i<children.length; i++) {
                copyDirectory(new File(srcDir, children[i]),new File(dstDir, children[i]));
            }
        } else {
		InputStream in = new FileInputStream(srcDir);
	    OutputStream out = new FileOutputStream(dstDir);
    
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }	
 
        in.close();
        out.close();
}
}
}
 
 
AccumulativeRunnable.java 
 
import java.util.*;
import java.lang.reflect.Array;
import javax.swing.SwingUtilities; 
abstract class AccumulativeRunnable<T> implements Runnable {
    private List<T> arguments = null;
    private Class<?> componentType = null;     
    protected abstract void run(T... args);     
    public final void run() {
        run(flush());
    }    
    public final synchronized void add(T... args) {
        if (componentType == null) {
            componentType = (Class<T>) args.getClass().getComponentType();
        }
        boolean isSubmitted = true;
        if (arguments == null) {
            isSubmitted = false;
            arguments = new ArrayList<T>();
        }
        Collections.addAll(arguments, args);
        if (!isSubmitted) {
            submit();
        }
    }
   
    protected void submit() {
        SwingUtilities.invokeLater(this);
    }
 
    private final synchronized T[] flush() {
        List<T> list = arguments;
        arguments = null;
        if (componentType == null) {
            componentType = Object.class;
        }
        T[] args = (T[]) Array.newInstance(componentType,
                                           list.size()); 
        list.toArray(args);
        return args;
    }
}
 
 
SwingPropertyChangeSupport.java 
 
 
import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeEvent;
import javax.swing.SwingUtilities;
import java.beans.*;
public final class SwingPropertyChangeSupport extends PropertyChangeSupport {
   
    public SwingPropertyChangeSupport(Object sourceBean) {
        this(sourceBean, false);
    }   
    public SwingPropertyChangeSupport(Object sourceBean, boolean notifyOnEDT) {
        super(sourceBean);
        this.notifyOnEDT = notifyOnEDT;
    }
    
    public void firePropertyChange(final PropertyChangeEvent evt) {
        if (evt == null) {
            throw new NullPointerException();
        }
        if (! isNotifyOnEDT()
            || SwingUtilities.isEventDispatchThread()) {
            super.firePropertyChange(evt);
        } else {
            SwingUtilities.invokeLater(
                new Runnable() {
                    public void run() {
                        firePropertyChange(evt);
                    }
                });
        }
    }
    public final boolean isNotifyOnEDT() {
        return notifyOnEDT;
    }
    static final long serialVersionUID = 7162625831330845068L;    
    private final boolean notifyOnEDT;
}
 
 
SwingWorker.java 
 
 
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import javax.swing.SwingUtilities;
import java.beans.*;
 
public abstract class SwingWorker<T, V> implements Runnable, Future<T> {     
    private static final int MAX_WORKER_THREADS = 10;     
    private volatile int progress;
    private volatile StateValue state;
    private final FutureTask<T> future;
    private final SwingPropertyChangeSupport propertyChangeSupport;
    private AccumulativeRunnable<V> doProcess;
    private AccumulativeRunnable<Integer> doNotifyProgressChange;
    private static ExecutorService executorService = null;
    public enum StateValue {PENDING,STARTED,DONE  };
 
    public SwingWorker() {
        Callable<T> callable = 
                new Callable<T>() {
                    public T call() throws Exception {
                        setState(StateValue.STARTED);
                        return doInBackground();
                    }
                };
 
        future = new FutureTask<T>(callable) {
                       @Override
                       protected void done() {
                           doneEDT();
                           setState(StateValue.DONE);
                       }
                   };
 
       state = StateValue.PENDING;
       propertyChangeSupport = new SwingPropertyChangeSupport(this, true);
 
       doProcess = null;
       doNotifyProgressChange = null;
    }
    
    protected abstract T doInBackground() throws Exception ;
    public final void run() {
        future.run();
    }
    protected final void publish(V... chunks) {
        synchronized (this) {
            if (doProcess == null) {
                doProcess = new AccumulativeRunnable<V>() {
                    @Override
                    public void run(V... args) {
                        process(args);
                    }
                };
            }
        }
        doProcess.add(chunks);
    }
 
    protected void process(V... chunks) {
    }
 
    protected void done() {
    }
    protected final void setProgress(int progress) {
        if (progress < 0 || progress > 100) {
            throw new IllegalArgumentException("the value should be from 0 to 100");
        }
        int oldProgress = this.progress;
        this.progress = progress;
        synchronized (this) {
            if (doNotifyProgressChange == null) {
                doNotifyProgressChange = 
                    new AccumulativeRunnable<Integer>() {
                        @Override
                        public void run(Integer... args) {
                            firePropertyChange("progress", 
                               args[0], 
                               args[args.length - 1]);
                        }
                    };
            }
        }
        doNotifyProgressChange.add(oldProgress, progress);
    }
    public final int getProgress() {
        return progress;
    }
    public final void execute() {
        getWorkersExecutorService().execute(this);
    }
    public final boolean cancel(boolean mayInterruptIfRunning) {
        return future.cancel(mayInterruptIfRunning);
    }
    public final boolean isCancelled() {
        return future.isCancelled();
    }
    public final boolean isDone() {
        return future.isDone();
    }
    public final T get() throws InterruptedException, ExecutionException {
        return future.get();
    }    
    public final T get(long timeout, TimeUnit unit) throws InterruptedException,
            ExecutionException, TimeoutException {
        return future.get(timeout, unit);
    }
    public final void addPropertyChangeListener(PropertyChangeListener listener) {
        getPropertyChangeSupport().addPropertyChangeListener(listener);
    }
    public final void removePropertyChangeListener(PropertyChangeListener listener) {
        getPropertyChangeSupport().removePropertyChangeListener(listener);
    }
    public final void firePropertyChange(String propertyName, Object oldValue,
            Object newValue) {
        getPropertyChangeSupport().firePropertyChange(propertyName,
            oldValue, newValue);
    }
 
    public final PropertyChangeSupport getPropertyChangeSupport() {
        return propertyChangeSupport;
    }
 
    // PropertyChangeSupports methods END
 
    /**
     * Returns the {@code SwingWorker} state bound property.
     * 
     * @return the current state
     */
    public final StateValue getState() {
        /*
         * DONE is a special case
         * to keep getState and isDone is sync
         */
        if (isDone()) {
            return StateValue.DONE;
        } else {
            return state;
        }
    }
 
    private void setState(StateValue state) {
        StateValue old = this.state;
        this.state = state;
        firePropertyChange("state", old, state);
    }
    
    private void doneEDT() {
        Runnable doDone = 
            new Runnable() {
                public void run() {
                    done();
                }
            };
        if (SwingUtilities.isEventDispatchThread()) {
            doDone.run();
        } else {
            SwingUtilities.invokeLater(doDone);
        }
    }    
    private static synchronized ExecutorService getWorkersExecutorService() {
        if (executorService == null) {
            //this creates non-daemon threads. 
            ThreadFactory threadFactory = 
                new ThreadFactory() {
                    final ThreadFactory defaultFactory = 
                        Executors.defaultThreadFactory();
                    public Thread newThread(final Runnable r) {
                        Thread thread = 
                            defaultFactory.newThread(r);
                        thread.setName("SwingWorker-" 
                            + thread.getName());
                        return thread;
                    }
                };     
            executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS,
                                         1L, TimeUnit.SECONDS,
                                         new LinkedBlockingQueue<Runnable>(),
                                         threadFactory) {
 
                    private final ReentrantLock pauseLock = new ReentrantLock();
                    private final Condition unpaused = pauseLock.newCondition();
                    private boolean isPaused = false;
                    private final ReentrantLock executeLock = new ReentrantLock();
                    
                    @Override
                    public void execute(Runnable command) {                        
                        executeLock.lock();
                        try {
 
                            pauseLock.lock();
                            try {
                                isPaused = true;
                            } finally {
                                pauseLock.unlock();
                            }
                            
                            setCorePoolSize(MAX_WORKER_THREADS);
                            super.execute(command);
                            setCorePoolSize(0);
                            
                            pauseLock.lock();
                            try {
                                isPaused = false;
                                unpaused.signalAll();
                            } finally {
                                pauseLock.unlock();
                            }
                        } finally {
                            executeLock.unlock();
                        }
                    }
                    @Override 
                    protected void afterExecute(Runnable r, Throwable t) { 
                        super.afterExecute(r, t);
                        pauseLock.lock();
                        try {
                            while(isPaused) {
                                unpaused.await();
                            }
                        } catch(InterruptedException ignore) {
                            
                        } finally {
                            pauseLock.unlock();
                        }
                    }
                };
        }
        return executorService; 
    }
}
can any one pls solve this problem. thanks in advance.
Reply With Quote
  (#2 (permalink)) Old
Member
 
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Sep 2008
Default I am having the same problem - 09-26-2008, 08:48 AM

did you manage to solve it?
I am running into the same problem
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Using Applet in Dynamic Web Project in eclipse armali Java 1 10-10-2008 05:12 PM
TransportException in applet reloading randy ortan Java 0 09-13-2008 07:25 AM
Applet to upload files and folder over HTTP jfileupload Java 2 03-11-2008 05:29 AM


Copyright 1997-2009, DZone, Inc.
vBulletin Skin developed by: vBStyles.com