logo
down
shadow

Java Threads Object Lock


Java Threads Object Lock

By : user2172946
Date : October 22 2020, 08:10 AM
will be helpful for those in need
There will be two locks, subject1.o and subject2.o ..., which means both methods will run independently and at the same time.
code :
public void run() {
    subject1.m1();
    subject2.m1();  
}


Share : facebook icon twitter icon
Lock object in Java threads for certain period

Lock object in Java threads for certain period


By : rust20
Date : March 29 2020, 07:55 AM
seems to work fine I think you can implement this based on Semaphore, though you'll have to implement the monitoring functionality yourself by setting a timestamp when a lock is acquired, checking it periodically and interrupting the thread holding the lock if it's held too long.
The LockSupport class also looks like it could help.
Java read & write lock requirement, with lock and release from different threads

Java read & write lock requirement, with lock and release from different threads


By : user3373352
Date : March 29 2020, 07:55 AM
I hope this helps . You can use a semaphore in this scenario and not require a busy wait for the shutdown() call. The way to think of it is as a set of tickets that are handed out to workers to indicate that they are in-flight. If the shutdown() method can acquire all of the tickets then it knows that it has drained all workers and there is no activity. Because #acquire() is a blocking call the shutdown() won't spin. I've used this approach for a distributed master-worker library and its easy extend it to handle timeouts and retrials.
code :
Executor executor = // ...
final int permits = // ...
final Semaphore semaphore = new Semaphore(permits);

void schedule(final Runnable task) {
  semaphore.acquire();
  try {
    executor.execute(new Runnable() {
      @Override public run() {
        try {
          task.run();
        } finally {
          semaphore.release();
        }
      }
    });
  } catch (RejectedExecutionException e) {
    semaphore.release();
    throw e;
  }
}

void shutDown() {
  semaphore.acquireUninterruptibly(permits);

  // do stuff
}
java: If notify() is always called before the lock release, how could a waiting threads acquire this same lock?

java: If notify() is always called before the lock release, how could a waiting threads acquire this same lock?


By : LvChengbin
Date : March 29 2020, 07:55 AM
it helps some times Yes, your explanation is correct.
When you call wait() on an object, the calling thread will be added to the object's wait set. When it is notify()ied, it will be removed from that wait set, and perform a lock action on the object (it's within a synchronized block on that object). That lock action will block the current thread until it is complete, ie. locked the object monitor.
H2O producer java threads lock , reentrant lock

H2O producer java threads lock , reentrant lock


By : David Xie
Date : March 29 2020, 07:55 AM
This might help you You are signaling on a condition but there is no corresponding wait. Moreover, there is a typo - calling hydrogenProducer() from both threads (Thread o and Thread h)
I assume you want to produce two Hs before producing O. It doesn't matter whether two Hs is produced by the same thread or two different threads. I have used randomSleep() to demonstrate this situation.
code :
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class H2OProducer {
    static final int H2O_COUNT = 1_000;
    static final Random rand = new Random();

    static final Lock lock = new ReentrantLock(true);
    static final Condition oxzWait = lock.newCondition();
    static final Condition hydWait = lock.newCondition();

    static volatile int hydCount = 0;

    public static void main(String[] args) {
        try {
            Thread h1 = new Thread(() -> {
                try {
                    hydrogenProducer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            Thread h2 = new Thread(() -> {
                try {
                    hydrogenProducer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            Thread o = new Thread(() -> {
                try {
                    oxygenProducer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

            h1.setName("H1-Producer");
            h2.setName("H2-Producer");
            o.setName("Ox-Producer");

            h1.start();
            h2.start();
            o.start();

            try {
                h1.join();
                h2.join();
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
        }

    }

    public static void hydrogenProducer() throws InterruptedException {
        for (int i = 0; i < H2O_COUNT; i++) {
            lock.lock();
            try {
                while (hydCount == 2) {
                    hydWait.await();
                }

                hydCount++;
                System.out.println(Thread.currentThread().getName()+ ": H produced - " + i);

                if (hydCount == 2) {
                    oxzWait.signalAll();
                }
            } finally {
                lock.unlock();
            }

            randomSleep();
        }
    }

    public static void oxygenProducer() throws InterruptedException {
        for (int i = 0; i < H2O_COUNT; i++) {
            lock.lock();
            try {
                while (hydCount < 2) {
                    oxzWait.await();
                }

            hydCount = 0;
            System.out.println(Thread.currentThread().getName()+ ": O produced - " + i);
            System.out.println("");
            hydWait.signalAll();
            } finally {
                lock.unlock();
            }

            randomSleep();
        }
    } 

    public static void randomSleep() {
        int ms = rand.nextInt(500);
        try { 
            Thread.sleep(ms);
        } catch (InterruptedException ex) {
        }
    }
}
Many threads waiting to lock an object, but no thread is holding that lock

Many threads waiting to lock an object, but no thread is holding that lock


By : Eva Braun
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , The situation you describe sounds like a classic case of deadlock.
You could (perhaps should) an IDE such as Eclipse or IntelliJ Idea, through which you could debug your application step-by-step and understand exactly where it stops and what to do.
Related Posts Related Posts :
  • Interrupt CompletableFuture with default value
  • Eclipse - Choosing servers in "Run on server" vs setting "Target Runtime"
  • Spring JPA doesn't validate bean on update
  • How is takeWhile different from filter?
  • Spring Scheduled Cron jobs firing at wrong time
  • JFrame window resizing on every compile. Different results every time
  • Kotlin unresolved reference :add after converting from Java code
  • How to use Neo4j APOC method " apoc.export.csv.query(query,file,config)" in Java program
  • Regex to include all spanish characters and number
  • Parsing and Mapping a JSON Object with Dynamic Properties
  • Which approach to building domain objects in Spring MVC is more correct?
  • Java Long Min and Max not exact as mentioned in docs
  • Selenium opens new tab after SendKeys
  • How to sort a large array of ints?
  • FitNessse Test can not find Fixture
  • Including Signed Libraries in Executable JAR with Maven
  • If and Else statement run on second iteration of while loop
  • Change class of disabled tab on change of dropdown value
  • Junit5 @ParameterizedTest How to pass array as one of parameter
  • Text message not being sent to a list of numbers but is sent when just one number is specified
  • Spring mapped servlet not called in jetty-maven-plugin
  • How to pace the consumption of a sqs queue using spring integration
  • Autowiring Not getting disabled using xml configuration
  • Maze solve and shortest path with Java BFS
  • Spinner updating only on user actions
  • Why are Java rules for protected access such as they are?
  • Modify parameter of method by value in annotation aspectJ
  • How to send sensitive data to a Liferay portlet from outside the Liferay portal
  • Does a server connection stay open if created inside a method?
  • JAR manifest Class-Path, use folder instead of jar
  • How to do a bulk update in Firestore
  • ItemArray.checklist.add() not appending string to ArrayList
  • How to move something on screen without other picture staying there
  • SpringBoot : No matching bean found exception
  • Implementing the Clonable interface, but don't have to override the clone() method
  • how can i get this code to choose a random word once from each array to print a sentence?
  • Static class to get connections from connection pool
  • Unable to start Chrome browser with user profile in Selenium
  • How to pass a object to be created as a parameter for a method in Java?
  • How to retry with hystrix
  • Loading key to KeyStore fails on Android Oreo
  • Spring+Velocity unsuccessful attempts to save object
  • Private constructor in Kotlin
  • Jetty:run fails with NoSuchMethodError with Spring 5
  • Cannot upload my Web Applicartion in Jboss7 EAP7 EAP
  • How to load a certificate from "Credential storage"?
  • Call Genexus procedure stub in Java environment
  • JavaFX clipping produces a 'lottery scratch ticket'-Effect
  • Using DateTimeFormatter on january first cause an invalid year value
  • Get all the output from Watson conversation using java
  • Java unable to open main class and jar file
  • How to override @override method from activity into another class
  • Adding Runtime VM parameters to intellij for Java 9
  • Java IBM MQ Client connected but not getting messages from queue
  • Questions of Tomcat SSL configuration
  • Stale JNLP files for <extension> (since Java 9?)
  • Properly set (system) properties in JUnit 5
  • Spring MVC Model within POST Method is empty
  • VSTS buildagent: Java 9
  • java.lang.NumberFormatException: For input string: "id" for Hibernate
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org