Objects running on threads

Hi everyone,
I have an engine that I have coded that provides a set of services to various applications. Currently the engine is single-threaded, meaning that if more than one person where to access the same instance of the engine there would be shared data violations. I'm sure that you know the drill...
So, I am about the add a "UserSpace" class to the engine. Each person that logs into the engine will be assigned a user space, within which is stored information that is pertinent to them (and is isolated from all other users).
I am familiar with using threads to perform lengthy operations (ie: making an object Runnable and calling the start() method to get things going). But I have never used threads in this way before.
What I mean is that I want to be able to assign a thread to each user space. In other words every user will have their own unique thread just for them. Method calls on the user space do not need to be synchronized because the information within them is, by definition, not shared. If the user space has to make calls to other areas of the engine then those methods would have to be synchronized but I can deal with that.
So how would I go about accomplishing this? Is it just a case of implementing Runnable as I normally do, calling start() and then make method calls?
Thanks in advance for your help. :)
Ben

I believe you could accomplish what you wish w/3 classes. In accordance with your example and subsequent explanation, they are as follows:
public class UserSpace {
private Object mDataThatIsNotShared; // etc.
public String methodOne() { /*some code */ }
public void methodTwo(String s) { /*some code */ }
public class Server {
// This class would accept socket connections. For each socket
// connection accepted, create an object of the third class called
// ServerThread (see below):
while (true) {
// The line below blocks until connection:
Socket socketAccepted=serverSocket.accept();
ServerThread srvrThrd=new ServerThread(socketAccepted);
srvrThrd.start();
public class ServerThread extends Thread {
private Socket mSocket;
private UserSpace userSpace;
ServerThread(Socket socket) {
mSocket=socket;
userSpace=new UserSpace(...); //See, each ServerThread owns its own
public void run() {
// Do whatever work you want w/UserSpace.
Of course, this is way overly simplistic...Does not take into account the fact that you could have unlimited threads...i.e., your Server class needs to implement some sort of thread pool, etc.
Does this help you?
--Mike                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Having 2 objects running in separate threads

    I am accessing cobol programs using the microfocus runtime for java. The problem with it is that a you can only run one instance of a cobol program at the same time, unless they are in separate threads.
    Example:
    CobolTextSearch cobol1 = new CobolTextSearch();
    CobolTextSearch cobol2 = new CobolTextSearch();
    cobol1.execute("FAMILY");
    cobol2.execute("HISTORY");
    System.out.println(cobol1.getRecord());
    System.out.println(cobol2.getRecord());The output of this program results in HISTORY for cobol1 and HISTORY for cobol2. Where as if they were run in separate threads, I would have got FAMILY for cobol1.
    So my question is, is there any way I can run these two objects in separate threads so that any time I access the object it will be in its own thread? I cant just run them in separate threads on the execute because each getRecord is interfacing with cobol. After execute I want to be able to read values from the cobol files to see if they match without having to read each record into memory on the java side.

    No you are not missing anything, you just create a new thread each time you run something or you have to make a setter method to accept parameters for the next run and then a seperate method to actually make your routine execute.
    public void setTask(String s){
      task2Execute = s; //task2Execute is global to the methods
    public boolean runTask(){
      CobolTextSearch cobol = new CobolTextSearch();
      cobol1.execute(task2Execute);
    //  other logic
    }Here is what the docs say about threads: A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

  • How to pass a "user defined" object to a thread?

    Hi...
    I have created an object say 'obj1' . I want to pass to a thread say 'T1' .
    The thread T1 implements the runnable class.
    I need to pass the "obj1" object to the T1 for it to be processed in the "run" method of T1.
    As far as I have seen there is no thread constructor in Java that accepts an object created by the user.
    My question is there any way to pass an object to a thread? and if so how can it be done?

    You can just add your own method to the class. Then call that method to pass the object to the thread before you call start on the thread.
    class MyThread implements Runnable
       public void run()
          userObj.whatever();
       public void addObj(Object obj)
          userObj = obj;
       Object userObj = null;
    // your code
    MyThread thread = new MyThread();
    thread.addObj(myObj);
    thread.start();As long as you don't call start before your pass the object to your thread, then you won't have a problem. Hope this helps.

  • Accessing Object using mutliple threads

    I created a class that creates 2 threads and both thread calls a method ( not synch..). In the method i create a new object.
    Here is the code for it.
    class ggh{
        public void m1(){
            ss s1= new ss();      // Simple class having 2 fields(int and string) and their getter setters
            System.out.println("S1 for thread #" + Thread.currentThread().getName() + "  ==> " + s1.toString()  );
            if(Thread.currentThread().getName().equals("Thread-0"))  // thread #1
                try {
                    Thread.sleep(1000);      // -------------> 1
                s1.setA(2);                           // --------------> 2
                System.out.println("Settin s1 = null " + Thread.currentThread().getName());
                    s1 = null;                         //  ---------------> 3
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
            System.out.println("s1 a==>" + s1.getA() + "::" + Thread.currentThread().getName() + " :: " + s1.toString());         //----------------> 4
        public static void main(String[] args) {
            final ggh g1 = new ggh();
            Thread t1 = new Thread(){
                public void run(){
                    g1.m1();
            Thread t2 = new Thread(){
               public void run(){
                        g1.m1();
            t1.start();
            t2.start();
    }when i execute this code, my output is totally unpredictable. Here are some of the outputs i got.
    ************** 1 The code creates the same object for both threads
    S1 for thread #Thread-0 ==> vom.cdd.ss@defa1a
    S1 for thread #Thread-1 ==> vom.cdd.ss@defa1a
    s1 a==>1::Thread-1 :: vom.cdd.ss@defa1a
    Settin s1 = null Thread-0
    java.lang.NullPointerException
         at vom.cdd.ggh.m1(ggh.java:39)
         at vom.cdd.ggh$1.run(ggh.java:46)
    ************** 2 objects are different now.
    S1 for thread #Thread-0 ==> vom.cdd.ss@f5da06
    S1 for thread #Thread-1 ==> vom.cdd.ss@defa1a
    s1 a==>1::Thread-1 :: vom.cdd.ss@defa1a
    Settin s1 = null Thread-0
    java.lang.NullPointerException
         at vom.cdd.ggh.m1(ggh.java:39)
         at vom.cdd.ggh$1.run(ggh.java:46)
    ************* 3 [Here nullpointer exception occurs before the null message is printed[/b]
    S1 for thread #Thread-0 ==> vom.cdd.ss@defa1a
    S1 for thread #Thread-1 ==> vom.cdd.ss@defa1a
    s1 a==>1::Thread-1 :: vom.cdd.ss@defa1a
    java.lang.NullPointerException
         at vom.cdd.ggh.m1(ggh.java:39)
         at vom.cdd.ggh$1.run(ggh.java:46)
    Settin s1 = null Thread-0
    So my question here is :
    when such kind of unsynch. access occurs for some method. then does there exists a different object [b]( a new memory is allocated ) for each thread
    or does there exist only one object and each thread has a different reference to it, and the thread can manipulate its properties.
    Or does there exist a different explanation for this kind of behaviour??
    One more thing, i dont wnat the method/a block of code to be synchronized.
    I also have another doubt but willl post it after this one get's cleared.
    Thanks in advance.
    Regards
    Akshat Jain

    2 objects are different nowThey are not different at all. Address can differ at
    each invocation.What do u mean that they are not different at all.
    if they have different object's then obviously their address are different and henc the objects too.
    am i getting this wrong??

  • How to keep an application level object running with SunIDM?

    We are working on intergrate a gmail project with SunIDM. We need an application level object running with SunIDM so it will maintain a token generated from Gmail side. In anther servlet project, I had this object saved in the attribute of the ServletContext, then other session level servlet could share this attribute anytime. Is there a way to store attribute in Servlet Context and have it shared by different user session in SunIDM? I have been reading documents and searched this forum, haven't find any topics related how to maintain an application level object live. Hopefully that I can get some hint here.
    Thank you so much.

    Paul, Thank you so much for the further explaination. I don't think it will work since the token generated from gmail will expire every 24 hours.
    We are using the gdata library published from by gmail people, and I create a new UserService object and have it run in the application level. The UserService object will generate a token and renew it every 24 hours behind the scene. Here is how I implement it in my Servlet project:
    //to have a UserService object running at the application level:
    public class GmailUserService extends HttpServlet {
    public void init(ServletConfig config) throws ServletException{
    super.init();
    userService = new UserService(myApplication);
    config.getServletContext().setAttribute("gmailUserService", userService);
    //to access this UserService object from other servlet in each user session:
    UserService userService = (UserService)servletContext.getAttribute("gmailUserService");
    Gmail will trigger an error if we create a new UserService object for each user. They recommend to have all the user to share one UserService object. I am looking for similar approach in SunIDM.
    Thank you again, Paul, for trying to help.

  • Reading the output from a object running in the local machine.

    Reading the output from a object running in the local machine.
    By using a signed applet i am lunching a small application that returns an image object, how to read that without storing it in the hard disk.
    Which means i need to read the image object return by the local application using applet or jsp .
    i am using tomacat and an html page with an applet with it to lunch the application.

    You can write that image in a binary format using OutputStream for System.out and then read it in your applet.

  • How to run a thread for second time ?

    I have a written a ThreadPool, but I found that basically a thread is not running for the second time. i.e First i call run() method and call stop(). If i call again run() method for the same thread, it is not running. What should I do, If i want to run the thread for the second time ?
    class NewThread implements Runnable {
    String name;
    NewThread(String a) {
    name=a;
    public void run() {
    try{
    for(int i=0;i<5;i++) {
    System.out.println("Thread :" + name + " #" +i);
    Thread.sleep(5);
    catch (Exception e) {
    e.printStackTrace();
    class threadRunnableTest {
    public static void main (String args[]) {
    Runnable runnable=new NewThread("BaSkAr");
    Thread thread = new Thread(runnable);
    try{
    System.out.println("First Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("First Thread it to be stopped!!");
    thread.stop();
    System.out.println("Second Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("Second Thread it to be stopped!!");
    thread.stop();
    catch (Exception e) {
    e.printStackTrace();

    baskark wrote:
    I have a written a ThreadPool, but I found that basically a thread is not running for the second time. i.e First i call run() method and call stop(). If i call again run() method for the same thread, it is not running. What should I do, If i want to run the thread for the second time ?
    class NewThread implements Runnable {
    String name;
    NewThread(String a) {
    name=a;
    public void run() {
    try{
    for(int i=0;i<5;i++) {
    System.out.println("Thread :" + name + " #" +i);
    Thread.sleep(5);
    catch (Exception e) {
    e.printStackTrace();
    class threadRunnableTest {
    public static void main (String args[]) {
    Runnable runnable=new NewThread("BaSkAr");
    Thread thread = new Thread(runnable);
    try{
    System.out.println("First Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("First Thread it to be stopped!!");
    thread.stop();
    System.out.println("Second Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("Second Thread it to be stopped!!");
    thread.stop();
    catch (Exception e) {
    e.printStackTrace();
    It's usually helpful to check the documentation:
    [http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#start()|http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#start()]
    start
    public void start()Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
    The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
    It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
    So, make a new java.lang.Thread

  • How do I run a thread without its panel.

    I have created a vi in my application that I run as a thread. I run the thread by using an invoke node.
    When I am testing under LabView everything is fine but when I create the executable I have found problems.
    As I am starting the thread with an invoke node, the vi does not show in the application builder unless I add it as a top level vi. When I add it as a top level vi, the panel is shown when I run the application.
    I don't want to show the panel because firstly theres nothing on it anyway and secondly it looks untidy.
    Dave.

    Brian
    I tried that already with no effect. I have attached an example of my problem. This shows a meter on the front panel. A vi running as a thread writes a value to a global every 20ms and this is then read by the front panel and written to the meter.
    Dave.
    Attachments:
    Thread_test.zip ‏18 KB

  • How do i run two threads with different sleep times?

    How do i run two threads with different sleep times?
    Ive got thread A and thread B, they both update a jpanel.
    They both start when i press the start button.
    However thread A updates every 250ms and thread B updates every 1000ms. i cant just run them both at 250ms becuase this will mess it up.
    So for every four runs of thread A i want thread b to only be run once
    Does anyone know how to do this?
    Thanks, Ant...

    ok, ive done it but now i cant stop it!
    ive added buttons to start and stop, the start button works but the stop button doesnt. why doesnt "t.stop();" work?
        public void run() {
            while(t == Thread.currentThread()) {
                System.out.println("No " + t.getName());
                if (t.getName().equals("1")){
                    try {
                        t.sleep(1000); // in milliseconds
                    } catch (InterruptedException e) {}
                } else{
                    try {
                        t.sleep(250); // in milliseconds
                    } catch (InterruptedException e) {}
        }

  • How to run multiple Thread using Scheduler's in 1.5

    Hi,
    I have a scenario, in which I have to run a Thread at every 15 minutes, If the first Thread is not Finished in 15 min then new Thread has to start.
    Currently I implemeted with java 1.5 schedulers, but the problem is if my first Thread is taking more than 15 min, then no new Thread is starting.
    Following is my Code:
    TestAccountingThread accountingThread = new TestAccountingThread();
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
    scheduler.scheduleAtFixedRate( accountingThread, 0, 60, SECONDS );
    Can any one help on this, This is really urgent.
    Regards,
    Suman

    if my first Thread is taking more than 15 min, then no new Thread is startingIf it takes more than 15 min, manually run a new scheduler with initial-delay=0 and shutdown the current one when the current execution is finished --- and repeat this logic in a conditional loop.
    Could this be what you want?

  • Running a Thread in Oracle

    I have a java stored procedure that has a Thread in it. The Thread is bog standard (extends Thread) and all is does is sleep for 20 seconds:
                MyThread myThread = new MyThread();
                first.start(); 
                first.sleep(20000);
                first.finished = true;                    Obviously setting the 'finished' boolean to true breaks out of the run method.
    The problem is that when i run this on my desktop it sleeps for 20 seconds then exits. When I load this class into Oracle it never seems to wake up!
    Am I missing something here? Can you run new Threads in a Java Stored Procedure?
    thanks
    m

    >
    Can you run new Threads
    in a Java Stored Procedure?Probably.
    Sounds like a really bad idea to me though.

  • Re-running a Thread

    Hi all,
    I have a problem with re-running a Thread. I try to reun a Thread via its start()-method. The first time everything works fine. The second time (after the Thread finishes his first execution) the run()-method is never invoked when calling start(). Is this a bug or is there no way to re-use a Thread. Do I have to construct a new Thread instead of re-using the old one?
    Thanks for any hint, Mathias

    You can only call start() once. When the thread exits its run method, then this thread is stopped and you cannot run it again.
    Take a look at the SwingWorker example on how to reuse a thread. It works something like this:
    public void run() {
      while (running) {
        // wait until a new task is received
        // run the task
    public void newTask(Runnable task) {
      // notify the thread about this new task
    public void stopThread() {
      running = false;
      // notify the thread in case it is sleeping
    }

  • Immutable Objects in multi threaded application - how does it works?

    Hi
    I have this code will work in multithreaded application.
    I know that immutable object is thread safe because its state cannot be changed. And if we have volatile reference, if is changed with e.g.
    MyImmutableObject state = MyImmutableObject.newInstance(oldState, newArgs); i.e. if a thread wants to update the state it must create new immutable object initializing it with the old state and some new state arguments) and this will be visible to all other threads.
    But the question is, if a thread2 starts long operation with the state, in the middle of which thread1 updates the state with new instance, what will happen? Thread2 will use reference to the old object state i.e. it will use inconsistent state? Or thread2 will see the change made by thread1 because the reference to state is volatile, and in this case thread1 can use in the first part of its long operation the old state and in the second part the new state, which is incorrect?
    Therad1:                                                  Thead2:
    State state = cache.get();     //t1                  
    Result result1 = DoSomethingWithState(state);     //t1    
                               State state = cache.get(); //t2
       ->longOperation1(state); //t1
                               Result result2 = DoSomethingWithState(state); //t2
                                   ->longOperation1(state); //t2
       ->longOperation2(state);//t1
    cache.update(result1);    //t1             
                                   ->longOperation2(state);//t2
                               cache.update(result2);//t2
    Result DoSomethingWithState(State state) {
       longOperation1(state);
       //Imaging Thread1 finish here and update state, when Thread2 is going to execute next method
       longOperation2(state);
    return result;
    class cache {
    private volatile State state = State.newInstance(null, null);
    cache.update(result) {
       this.state = State.newInstance(result.getState, result.getNewFactors);
    get(){
    return state;
    }

    Please don't cross post
    http://stackoverflow.com/questions/6803487/immutable-objects-in-multi-threaded-application-how-does-it-work

  • Running a thread for a specified time

    my main program has 10 threads. i want to run each thread for 30 secs . but if one thread is on progress it may be allowed some time to complete its task otherwise evrbody should return after 30 secs.how can i do it ?
    thankx

    code is hanging...
    also how do i do >>if one thread is on progress it may be allowed some time to complete its task otherwise evrbody should return after 30 secs
    class Shared
    boolean stop=false;
    // do nothing but helps only for synchronisation
    class ThreadProducer1 extends Thread
    {    Shared obj;
         public void run()
         {   long endTime = System.currentTimeMillis() + 30 * 1000;
             long currentTime;
              for (int k=0;k<1000;k++)
              {System.out.println("thread1");     // doing its work
             currentTime=System.currentTimeMillis();
              if (currentTime>endTime) break;
    class ThreadProducer2 extends Thread
    {   Shared obj;
         public void run()
         {   long endTime = System.currentTimeMillis() + 30 * 1000;
             long currentTime;
              for (int k=0;k<1000;k++){
              System.out.println("thread2");     // doing its work
              currentTime=System.currentTimeMillis();
              if (currentTime>endTime) break;}     // doing its work
    class ThreadProducer3 extends Thread
    {   Shared obj;
         public void run()
         {   long endTime = System.currentTimeMillis() + 30 * 1000;
             long currentTime;
              for (int k=0;k<1000;k++)
              System.out.println("thread 3");     // doing its work
              currentTime=System.currentTimeMillis();
              if (currentTime>endTime) break;
              }     // doing its work
    class Test
    public static void main(String argv[])
        try{
         ThreadProducer1 t1 = new ThreadProducer1();
         ThreadProducer2 t2 = new ThreadProducer2();
         ThreadProducer3 t3 = new ThreadProducer3();
         t1.start();
        t2.start();
         t3.start();
        Thread.sleep(30000); // main thread wakes up after 30 secs.
         }catch (InterruptedException ex)
             System.out.println("exception");

  • Using one object in multiple threads

    Are there any drawbacks in using one instance of an object in several threads simultaneously, if this object has no instance variables?
    I need to implement DAO in my project and I just wonder why DAOFactory every time creates a new DAO object, when DAO object doesn't have any instance variables?

    Are there any drawbacks in using one instance of an
    object in several threads simultaneously, if this
    object has no instance variables?
    I need to implement DAO in my project and I just
    wonder why DAOFactory every time creates a new DAO
    object, when DAO object doesn't have any instance
    variables?I don't think there are any problems with this. Since you have no instance variables there isn't really any overlap between the two threads.

Maybe you are looking for

  • IPod will not mount!!

    I'm having huge difficulties with my iPod 4g 20 gb. I own one emac (running tiger) and an imac (running jaguar). I hardly ever use my iPod with the imac but i decided to try it out and listen to the iPod straight through the imac speakers while worki

  • Image Processor won't run action correctly

    I have CS6 (CC) on a Mac (2013).  I wrote an action for saving my work.  In my normal .psd file, I use multiple layers for editing, etc.  I also use a group folder for my B&W conversion.  I made an action to utilize the saved .psd file to save both t

  • Colour profiles in Lion and windows 7 with fusion 3

    Hello - I am a new iMac  user and I also have windows 7x64 installed with fusion 3.   I am a keen photographer and use an external colour monitor calibrator - eye-one display 2  - not the latest version I know but it worked fine on my old PC running

  • Installment plan v/s payment schema

    Hello, Instalment paln and payment schema(Budget Billling) both does the same functions.If i am right what are the differences. which gives the higher flexibility?where, how , when we use????

  • About "javac" in MS-DOS

    i tried to use comand "javac" to compile my program in MS-DOS,but the system tell me that is an invalid command,why?then i compiled the program in JCreator,it generated a ".class" file in the directory,and then I can use "java" command to run the pro