Java-Gaming.org    
Featured games (91)
games approved by the League of Dukes
Games in Showcase (579)
games submitted by our members
Games in WIP (500)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Thread safety & synchronized  (Read 975 times)
0 Members and 1 Guest are viewing this topic.
Offline mauryr

Senior Newbie





« Posted 2006-07-15 18:30:00 »

Hello, I have a problem with thread safety on this block of code. Synchronized just seems to be ignored.. I am using a static variable to count the calls to it, and it's reaching 2 most of the times, while it should never go over 1. Am I doing something incredibly and terribly wrong or is this a bug? I also tried making the whole method synchronized, and it won't change anything.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
    //This method looks for an available model id. If none is found, it tries to discard an expendable model to make room.
   //If no expendable model, it returns -1 as an error code, and the model won't be loaded.
   public int createInFirstAvailableID(String fileName){
        int i=0;
      synchronized (this){
           
        ModelsManager.count++;
        System.out.println("Istances: "+ModelsManager.count);
        while(i<Configuration.getMaxModelCount() && models[i++]!=null);
       
        if(i<Configuration.getMaxModelCount()){ //I found an usable id
           System.out.println("Id found: "+ (i-1)+" for "+fileName);
            models[--i]=new Model3D(fileName);
            System.out.println("Model created: "+ i+" for "+fileName);

        ModelsManager.count--;  
            return i;
        }else{ //No available id, need to discard an expendable texture
           //if I get here it means all ids are taken, pointless to check on models[] again, just free up one with 0 istances
           i=0;
            while(i<Configuration.getMaxModelCount()){
                if(instanceCount[i]==0){  //Found one to discard
                   models[i].release();
                    models[i]=new Model3D(fileName);                    
        ModelsManager.count--;            
                    return i;                    
                }else{
                    i++;
                }                
            }
        ModelsManager.count--;            
            return -1;
        }    
        }
    }


Thanks..
Offline mauryr

Senior Newbie





« Reply #1 - Posted 2006-07-15 20:39:25 »

Ok.. since it didn't make any sense to have a threading problem there.. I went to find out if the lock I was acquiring was really the same.. and found this idiotic mistake..
The code was in a singleton class, and I made my mistake on the getInstance() method, where I forgot to specify the MyClass identifier while using the singletonInstance reference. This didn't fail to compile (as singletonInstance IS a member of the class, even if static) but didnt actually work as a static variable should. I don't really understand where the variable goes, if it's not in the "this" reference, it's not in the method stack and it's not a real static variable, then what is it? But ok, adding that fixed it.

Wrong code:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
  
public class MyClass{
  //Singleton instance pointer
   private static MyClass singletonInstance=null;
   
    protected MyClass() {
    }
   
    public static MyClass getInstance(){
        if(singletonInstance==null){
            singletonInstance=new MyClass();
        }        
        return singletonInstance;        
    }


Correct code:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
  

public class MyClass{
  //Singleton instance pointer
   private static MyClass singletonInstance=null;
   
    protected MyClass() {
    }
   
    public static MyClass getInstance(){
        if(MyClass.singletonInstance==null){
            MyClass.singletonInstance=new MyClass();
        }        
        return MyClass.singletonInstance;        
    }


Please let me know if what I typed here has some minor/major imprecisions.. or if anyone know why the first case still compiles.
Thanks.
Offline mauryr

Senior Newbie





« Reply #2 - Posted 2006-07-15 20:47:10 »

Fine fine... so after all it doesn't make any difference to use the first or the second code... The problem instead lies in the fact the getInstance method needs to be synchronized, what was happening was two different threads were calling it at the same time, and they actually instanced two different instances of this singleton class. By maintaining their own references to the returned instance, they would use two different instances, thus acquiring two different locks, and making a big mess later, when a new call to the getInstance method would cause the loss of this unwanted second instance.

Finally the fixed code..
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
public class MyClass{
  //Singleton instance pointer
   private static MyClass singletonInstance=null;
   
    protected MyClass() {
    }
   
    public synchronized static MyClass getInstance(){
        if(singletonInstance==null){
            singletonInstance=new MyClass();
        }      
        return singletonInstance;      
    }


Thanks to javaWorld on the flawed tutorial about singleton~
Thanks..
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline bahuman

Junior Member





« Reply #3 - Posted 2006-07-15 21:34:20 »

do you often talk to yourself like this?  Grin Tongue
Offline Kova

Senior Member





« Reply #4 - Posted 2006-07-16 02:56:44 »

i don't really understand what the hell are you trying to do mauryr, but if you wonder about locks just create a Object only for locking on him...

Object LockName = new Object();
synchronized (LockName) {...}
Offline mauryr

Senior Newbie





« Reply #5 - Posted 2006-07-16 08:58:39 »

Yes, I do that very often.. for some reason I spend hours on idiotic bugs, then I post a question and find the answer by myself....
To Kova: I already have my object I wanna lock on, the only problem was I thought there always was only a single instance of it, but there could be 2, which made 2 locks available, while I needed it to be singleton~ So the problem was not in the lock itself, but in the singleton pattern implementation, resulting flawed in this case because two different thread were concurrently calling the "side constructor" at the same time, thus creating two instances, one of which got lost after a few, losing important data which should have belonged to the one and only instance..
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

xsi3rr4x (35 views)
2014-04-15 18:08:23

BurntPizza (31 views)
2014-04-15 03:46:01

UprightPath (46 views)
2014-04-14 17:39:50

UprightPath (29 views)
2014-04-14 17:35:47

Porlus (46 views)
2014-04-14 15:48:38

tom_mai78101 (67 views)
2014-04-10 04:04:31

BurntPizza (127 views)
2014-04-08 23:06:04

tom_mai78101 (227 views)
2014-04-05 13:34:39

trollwarrior1 (192 views)
2014-04-04 12:06:45

CJLetsGame (199 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!