0

I am trying to learn concurrency in Java and not getting the desired results, why arent my locks working? I have tried every tutorial I can find and it is getting me closer, but not 100%

import java.util.concurrent.locks.*;
public class Concurrent extends Thread {
  private Object lock1;// = new Object();
  // static means the variable is shared by all objects, i.e. global
  static long counter = 0;
  static long threads = 10;
  static long count_each = 1000000;
  //private Object lock1 = new Object();
  private Object lock2 = new Object();
  ReentrantLock lock = new ReentrantLock();

  public synchronized void run() //Helps ++
  //public void run() 
  {    
    //synchronized (lock1) 
    //{
        //lock.lock();
        //Object lock1 = new Object();
        long count = count_each;   // local variable for this thread only
        while (count-- > 0) 
        {   
            //lock.lock();
            //try 
            //{
            Object lock1 = new Object();
            synchronized (lock1)  //Helps ++
            {
                counter++;
            }
            //}
            //finally 
            //{
            //    lock.unlock();
            //}
        }
        //lock.unlock();
    //}

  }

Previous attempts are commented out, I have tried just about every combination of everythnig you see.

Constantine
  • 1
  • 1
  • 4
  • 2
    All your lock objects are local to a `Concurrent` instance. Since `Concurrent` extends `Thread` I suspect that you create several `Concurrent` instances and call `start()` on them. But since each `Concurrent` instance has its own lock objects there is effectively no locking (to use locking you must do so on shared lock objects). – Thomas Kläger Dec 06 '22 at 06:24
  • FYI, `public synchronized void run()` is _always_ a bad idea. Declaring the `run()` function to be `synchronized` is the same as saying "This thread must not be allowed to do _anything at all_ while some other thread is doing some thing." But, if you don't allow threads to do work at the same time as each other, then what even is the point of creating threads? – Solomon Slow Dec 06 '22 at 15:55

1 Answers1

0

Your locks are not static, so every thread uses its own lock what renderes them useless.

SimGel
  • 293
  • 1
  • 10