LiveConnect Applet Architecture Bug with Thread utilization (with SSCCE!)

Discussion in 'Java' started by Richard Maher, Nov 20, 2010.

  1. Hi,

    I make no claim to being either a Javascript or JAVA expert so, before
    logging a bug report with SUN/Oracle, I would appreciate those here with
    relevant skills casting a critical eye of my small reproducer to see if the
    anomalies can be explained as simple pilot error rather than a bug in the
    plugin code.

    To reproduce the example locally, save the three text files below to the
    filenames and extensions specified. Then: -
    javac -cp "c:\Program Files\Java\jdk1.6.0_22\jre\lib\plugin.jar"
    OutThread.java
    javac -cp ".;c:\Program Files\Java\jdk1.6.0_22\jre\lib\plugin.jar"
    Sleeper.java
    jar -cf Sleeper2.jar Sleeper.class OutThread.class

    NB* The above specified the classpath so as to match my version and Windows
    location of the relevant bits from the SDK. Your OS, Java Version and SDK
    path may vary or may already be defined.

    Once you have compiled the two classes into the JAR, copy Sleeper2.jar and
    dyntest_embed.html to your web root directory. Pull up
    http://127.0.0.1/dyntest_embed.html with your FireBug/DeveloperTools Console
    window enabled and your JAVA console enabled and watch what happens. It can
    take up to 30,000 iterations or as little as 100 but you will see the
    "hang". (If you become impatient you can add further tabs with the same page
    (work the static vars) or load the browser instance and/or machine)

    What I observe and accuse the plugin of doing is allocating the wrong work
    to the wrong thread. That is, unlike the documented behaviour that can be
    seen at: -
    http://download.oracle.com/javase/6/docs/technotes/guides/jweb/applet/applet_execution.html#threads
    I believe that something makes the plugin lose track of the Thread pool and
    allocate the setBack()/notifyAll() call to the LiveConnect worker thread
    (when it should go to "Fred") and horror of horrors, my consumer thread
    "Fred" that should be exclusively processing jobs on the queue sometimes is
    allocated producer work (getNum()) which leads to an unavoidable deadlock
    :-(

    Actual example output: -
    [1]in getNum() 2490 caller [TO3] Thread Applet 1 LiveConnect Worker
    ThreadThread[Applet 1 LiveConnect Worker
    Thread,4,http://127.0.0.1/-threadGroup] hash 19c0bd6

    [1]Queueing work

    [1]Going for wait

    **[2]in getNum() 2409 caller [TO2] Thread
    FredThread[Fred,4,http://127.0.0.1/-threadGroup] hash 1827d1**

    [2]Queueing work

    [2]Going for wait


    This can be observed with FF and/or IE8 (Chrome doesn't seem to fail with
    only one tab but with multiple dyntest_embed.html tabs the results can be
    reproduced).

    Does it coincide with garbage collection? Is the code/logic fundamentally
    flawed? Is it a LiveConnect Thread management bug in desperate need of
    correction?

    Cheers Richard Maher

    OutThread.java
    ===========

    /**
    * Copyright (c) Richard Maher
    * All rights reserved.
    */
    import netscape.javascript.JSObject;
    import java.util.ArrayList;
    import java.util.concurrent.*;

    class OutThread extends Thread {
    ArrayList<JSObject> windows;
    BlockingQueue<JSObject> queue;
    JSObject item;

    public OutThread(String name, ArrayList<JSObject> windows,
    BlockingQueue<JSObject> queue) {
    super(name);
    System.out.println("Thread constructor");
    this.setDaemon(true);
    this.windows = windows;
    this.queue = queue;
    }

    private boolean readNext(){
    try {
    System.out.println("before take");
    item = queue.take();
    System.out.println("after take");
    } catch (InterruptedException e) {
    return false;
    }
    return true;
    }

    public void run() {
    while (readNext()) {
    // try {
    System.out.println("before call");
    // sleep((int)(Math.random() * 1000));
    try {
    item.call("dispatcher", null);
    } catch (Exception e){e.printStackTrace();}
    System.out.println("after call");
    // } catch (InterruptedException e) {break;}
    }
    System.out.println("DONE!");
    }
    }

    Sleeper.java
    ========
    /**
    * Copyright (c) Richard Maher
    * All rights reserved.
    */
    import java.applet.Applet;
    import netscape.javascript.JSObject;
    //import netscape.javascript.JSException;
    //import java.lang.InterruptedException;
    import java.util.ArrayList;
    import java.util.concurrent.*;

    public class Sleeper extends Applet {
    private int myNum = 0;
    private int myInstance = 0;
    private JSObject browser;
    private final Object lock = new Object();
    private boolean initFlag = false;
    private boolean idle = true;

    private static OutThread writer;
    private volatile static int appletIndex = 0;
    private volatile static ArrayList<JSObject> windows = new
    ArrayList<JSObject>();
    private static BlockingQueue<JSObject> queue = new
    ArrayBlockingQueue<JSObject>(5);

    public synchronized void init() {
    super.init();
    Thread curr = Thread.currentThread();
    System.out.println(" In Init() " + curr.getName() +
    curr + " hash " + Integer.toHexString(curr.hashCode()));

    try {
    browser = JSObject.getWindow(this); }
    catch (netscape.javascript.JSException e) {
    e.printStackTrace(); }
    catch (Exception e) {
    e.printStackTrace(); }

    synchronized(windows){
    appletIndex++;
    myInstance = appletIndex;
    windows.add(browser);
    if (writer == null){
    writer = new OutThread("Fred", windows, queue);
    writer.start();
    }
    }
    /**
    System.out.println("Before sleep call");
    try {
    Thread.sleep(1000);
    }
    catch (InterruptedException e){
    e.printStackTrace();
    }
    System.out.println("After sleep call");
    */
    myNum = 33;
    initFlag = true;
    }

    public synchronized boolean isDone() {
    Thread curr = Thread.currentThread();
    System.out.println(" In isDone() " + curr.getName() +
    curr + " hash " + Integer.toHexString(curr.hashCode()));
    return initFlag;
    }

    public synchronized int getNum(String caller, JSObject callback){
    if (!idle){
    System.out.println("******* boom *********");
    }
    idle = false;
    int i = myNum++;
    Thread curr = Thread.currentThread();
    System.out.println("["+myInstance+"]"+"in getNum() " + myNum + "
    caller " +
    caller + " Thread " + curr.getName() +
    curr + " hash " + Integer.toHexString(curr.hashCode()));

    try {
    synchronized (lock){
    System.out.println("["+myInstance+"]"+"Queueing work");
    queue.put(callback);
    System.out.println("["+myInstance+"]"+"Going for wait");
    lock.wait();
    // Thread.sleep(1000);
    }
    }
    catch (InterruptedException e){
    e.printStackTrace();
    }

    System.out.println("["+myInstance+"]"+"After wait call " + i);
    idle = true;
    return i;
    }

    public void setBack(String caller){
    Thread curr = Thread.currentThread();
    System.out.println("["+myInstance+"]"+"in setBack() " + myNum + "
    caller " +
    caller + " Thread " + curr.getName() +
    curr + " hash " + Integer.toHexString(curr.hashCode()));

    synchronized (lock){
    lock.notifyAll();
    }
    System.out.println("["+myInstance+"]"+"After notify");
    }

    public synchronized void destroy ()
    {
    System.out.println("["+myInstance+"]"+"Shutting down");
    if (writer != null){
    writer.interrupt();
    try {
    writer.join();
    }
    catch (InterruptedException e){
    e.printStackTrace();
    }
    writer = null;
    }

    System.out.println("["+myInstance+"]"+"Checked - out");
    super.destroy();
    }
    }


    dyntest_embed.html
    ==============

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

    <html>
    <head>
    <style>

    body
    {
    background-color: aliceblue;
    color: black;
    font-family: Georgia;
    font-size: 12px;
    }

    </style>

    <script type="text/javascript">

    var callNum = 0;
    var chanG;
    var activeTesters = [];
    var ctrl;

    function load()
    {
    var objectTag = "<object ";

    if (/Internet Explorer/.test(navigator.appName)) {
    objectTag = objectTag +
    'classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" ';
    } else {
    objectTag = objectTag +
    'type="application/x-java-applet" ' +
    'archive="http://127.0.0.1/Sleeper2.jar" ';
    }

    objectTag = objectTag +
    'width= "0" height= "0" id="TestApp">' +
    '<param name="archive" value="Sleeper2.jar">' +
    '<param name="codebase" value="http://127.0.0.1/">' +
    '<param name="code" value="Sleeper">' +
    '<param name="java_version" value="1.6+">' +
    '<param name="mayscript" value="true">' +
    '<param name="scriptable" value="true">' +
    '<param name="codebase_lookup" value="false">' +
    '</object>';

    var appletDiv = document.createElement("div");
    appletDiv.innerHTML = objectTag;

    try {
    document.body.appendChild(appletDiv);
    chanG = document.getElementById("TestApp");
    }
    catch(err) {
    alert("Tier3 unable to load applet: -\n" +
    (err.description||err.message));
    chanG = null;
    };

    if (chanG == null) {
    throw new Error("Tier3 was unable to initialize the applet");
    } else {
    try {
    if (!chanG.isDone())
    alert("*******RACE******");
    }
    catch(err) {
    chanG.setAttribute("id",null);
    chanG = null;
    throw new Error("Tier3 unable to load applet: -\n" +
    (err.description||err.message));
    }
    }

    ctrl = new blob();
    var tester1 = new tester(1,1000);
    var tester2 = new tester(2,300);
    var tester3 = new tester(3,500);

    }

    function tester(myId,timer){
    this.myId = myId;
    this.timer = timer;
    var sendIt = function(){ctrl.send("[TO"+myId+"]", fred);};
    var fred = function() {
    if (window.console) console.log("In callback");
    callNum++;
    document.mfForm.username.value=myId+"CB<:"+callNum;
    this.rendezvous();
    if (window.console) console.log("After setBack()");
    document.mfForm.state.value=myId+"CB>:"+callNum;
    setTimeout(sendIt,timer);
    }
    setTimeout(sendIt,0);
    activeTesters.push(this);
    return this;
    }

    function blob(){

    this.chan = chanG;

    return this;
    }

    blob.prototype = {

    send:
    function(msgBody, callback)
    {
    var chan = this.chan;
    var responseCnt = 0;
    var i = 0;

    var msgCandidate =
    {
    msgSeqNum : -1,
    chan : chan,
    callback : callback,

    dispatcher :
    function()
    {
    this.responseCnt++;

    try {
    callback.apply(this);
    }
    catch (err) {
    var errMsg = "Error calling callback
    routine: -\n";
    for (var prop in err) {
    errMsg += " Property: " + prop + " Value: " +
    err[prop] + "\n";
    }
    errMsg += " toString() = " + err.toString() +
    "\n";

    if (window.console) console.log("Client: " +
    errMsg);
    // document.write("Client: " + errMsg);
    throw new Error(errMsg);
    }
    },

    getResponseCnt:
    function() {
    return this.responseCnt;
    },

    rendezvous :
    function() {
    if (window.console) console.log("In rendezvous");
    chan.setBack("CB");
    }

    };

    if (window.console) console.log("Before SEND: " + msgBody);
    return chan.getNum(msgBody, msgCandidate);
    }
    }
    </script>
    </head>

    <body id="torso" onload="load()">
    <form name="mfForm">
    Something:
    <input
    name="username";
    type="text";
    size=20;
    />
    Stuff:
    <input
    name="state";
    type="text";
    size=20;
    />
    </form>
    </body>
    </html>
     
    Richard Maher, Nov 20, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. DKM
    Replies:
    1
    Views:
    546
  2. DKM
    Replies:
    9
    Views:
    1,150
    Andrew Thompson
    Jun 24, 2005
  3. Richard Maher
    Replies:
    5
    Views:
    501
    Richard Maher
    Nov 23, 2010
  4. Replies:
    0
    Views:
    139
  5. DKM
    Replies:
    6
    Views:
    197
Loading...

Share This Page