I have three objects: A, B, and C.
I need such synchronization so that blocks synchronized with objects A and B can be executed in parallel, and when block synchronized with objects A or block synchronized with objects B is executed, block synchronized with objects C cannot be executed. And when block synchronized with objects C is executed, blocks synchronized with objects A and B cannot be executed. I tried to use object C as list, and objects A and B as objects stored in this list, but it did not work. Please tell me, is it possible to somehow configure such synchronization?
import java.util.ArrayList;
import java.util.List;
public class Threads {
public List<Res> lst = new ArrayList();
public void startThreads(){
lst.add(new Res());
lst.add(new Res());
Thread t1 = new Thread(new work1());
Thread t2 = new Thread(new work2());
Thread t3 = new Thread(new work3());
t1.start();
t2.start();
t3.start();
}
public class work1 implements Runnable {
#Override
public void run() {
Method1();
}
}
public class work2 implements Runnable {
#Override
public void run() {
Method2();
}
}
public class work3 implements Runnable {
#Override
public void run() {
Method3();
}
}
public void Method1(){
synchronized (lst.get(0)/*obj A*/){
//some work
}
}
public void Method2(){
synchronized (lst.get(1)/*obj B*/){
//some work
}
}
public void Method3(){
synchronized (lst)/*obj C*/{
//some work
}
}
}
Class Res:
public class Res {
public int number = 0;
}
Class Main:
public class Main {
public static void main(String[] args) throws InterruptedException {
Threads t = new Threads();
t.startThreads();
}
}
In your case simplest (Not recommended) solution is to guard Block A and Block B with different monitor objects and guard Block C with the monitor obects of both A and B.
public void Method1(){
synchronized (A){
//some work
}
}
public void Method2(){
synchronized (B){
//some work
}
}
public void Method3(){
synchronized (A){
synchronized (B){
//some work
}
}
}
Same can be done using Locks as well.
public void Method1(){
lockA.lock();
try{
//some work
} finally {
lockA.unlock();
}
}
public void Method2(){
lockB.lock();
try{
//some work
} finally {
lockB.unlock();
}
}
public void Method3(){
lockA.lock();
try{
lockB.lock();
try{
//some work
} finally {
lockB.unlock();
}
} finally {
lockA.unlock();
}
}
Or you can use read/write lock as suggested by shmosel in the comments.
public void Method1(){
readWriteLock.readLock().lock();
try{
//some work
} finally {
readWriteLock.readLock().unlock();
}
}
public void Method2(){
readWriteLock.readLock().lock();
try{
//some work
} finally {
readWriteLock.readLock().unlock();
}
}
public void Method3(){
readWriteLock.writeLock().lock();
try{
//some work
} finally {
readWriteLock.writeLock().unlock();
}
}
You can also use CountDownLatch for the same purpose, though read/write lock is the easiest one.
I have two threads, A and B. I want the following:
I want to let A wait until B starts executing f(). Once B starts executing f(), A as well can continue its work.
If B is already executing f() when A informs B for its state, A can continue its work as well.
If however B finished executing f(), A has to wait until B starts executing f() again in the future.
In functions:
// executed by A only
public void waitForB() throws InterruptedException {
// keep waiting until B starts f()
}
// executed within aroundF() only
public void f() {
}
// executed by B only
public void aroundF() {
// 1. mark that we are executing f() and inform A
f()
// 2. unmark
}
I have been trying with Semaphore, Phaser and CyclicBarrier, but I have troubles to understand which to use here.
I managed to implement this with locking manually (see below), but I would like to understand which of the java.util.concurrent classes to use here.
private final Object lock = new Object();
private boolean executing = false;
public void waitForB() throws InterruptedException {
synchronized(lock) {
while(!executing) {
lock.wait();
}
}
}
public void f() {
}
public void aroundF() {
try {
synchronized(lock) {
executing = true;
lock.notify();
}
f();
} finally {
executing = false;
}
}
You can achieve the same semantics (and more) using java.util.concurrent.locks.Lock and an associated java.util.concurrent.locks.Condition, for instance:
public class MyClass {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private boolean executing = false;
public void waitForB() throws InterruptedException {
lock.lock();
try {
while (!executing) {
condition.await();
}
} finally {
lock.unlock();
}
}
public void f() {
}
public void aroundF() {
try {
lock.lock();
try {
executing = true;
condition.signal();
} finally {
lock.unlock();
}
f();
} finally {
executing = false;
}
}
}
I have two threads. The first changes the value of variable Data. And second one print the value if its value has changed. I am trying to do that second thread just print each time that the variable's value changed, but I don't reach success. Someone can help me?
thread 1
class someservice{
volatile int data;
Boolean Flag = false;
public void mymethod(){
flag = true;
for (Integer i = 1; i < sheet.getRows(); i++) {
data = someMethod(); //this method when called return a new
//value
}
flag = false;
...
}
}
thread 2
Promise p = task {
try {
while (true) {
if (engineService.getFlag()) {
print(someservice.data);
}else{
break;
}
}
} catch(Throwable t) {
...
}
}
Since you mention Promises, I infer you are familiar with future/ promise in +C++11
in java there is a similar approach, with future callable...
public class HW5 {
public static void main(String[] argv) throws InterruptedException, ExecutionException {
FutureTask<Boolean> myFutureTask = new FutureTask<>(new Callable<Boolean>() {
#Override
public Boolean call() throws Exception {
// implement the logic here and return true if everything was
// ok, false otherwise.
Thread.sleep(5000);
System.out.println("dddd");
return System.currentTimeMillis() % 2 == 0;
}
});
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(myFutureTask);
Boolean result = myFutureTask.get();
System.out.println("Done!");
}
}
FutureTask in a class that takes a callable which can return an Object after its job is done... in Order to execute the Future task you can use a Executor service, especifically calling the method execute, since you need to wait for the thread to do the job then is necessary that you call Future.get, that will basically blocks the main thread until the future is done, to verify the result, just read the variable result..
You could use the notify() and notifyAll() methods within thread. Check out this link: https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
public synchronized notifyJoy() {
joy = true;
notifyAll();
}
You have to look up more data about Concurrent programming,I can tell you now some basics,well,not so so basic,but i will do my best:
Here,you have a Monitor,it is an abstract concept,in resume,a Monitor is a
class with all it's
method using"syncronized"
as modifier, it means,
that only
one thread
can access
the method
at once.So,
in the
monitor is
the variable
that you
want to print,
and the"flag",
that tells you if
the variable
was modified.Finally,
you can
see the
most important thing,the"wait()"and"notify()"methods,
those method
stops the thread,or"play"
them again.
You ask
here in
the printValue() method, if your variable was changed, if the variable was'nt change, put the thead to sleep with the wait() method, and when the other
method changeValue() is executed, the value is modified, and the notify() method is called, waking up the thread, so, doing all this, you can guarantee three things:
Safety: meaning that the threads will do that you want
Absence of deadlock: meaning that the thread that is put to sleep, will be awake in the future.
Mutex: meaning that only one thread is executing the critical code, for example, the op. "++" is not atomic, is Subdivided inside in more the one action, create a local var, read the var, sum, and asign, so, if more than one thread are in the game, the value may not be consecutive, example:
i = 0;
i ++;
output: 1;
output: 2;
output: 3;
output: 5;
output: 4;
output: 7;
That could happen, and even so, that will happen in the next code, because there a more than one thread executing. Well, this is the way to program with several threads, more or less
public class Monitor {
private int value = 0;
public static boolean valueHasChanged = false;
public synchronized int changeValue(int newValue){
this.value = newValue;
Monitor.valueHasChanged = true;
this.notify();
return this.value + 1;
}
public synchronized void printValue(){
while(!Monitor.valueHasChanged){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(this.value);
Monitor.valueHasChanged = false;
}
public static void main(String[] args) {
Monitor ac = new Monitor();
BClass t1 = new BClass(ac);
AClass t2 = new AClass(ac);
t1.start();
t2.start();
}
public int getValue() {
return this.value;
}
}
Now the threads:
public class AClass extends Thread{
private Monitor ac;
public AClass(Monitor ac) {
this.ac = ac;
}
#Override
public void run() {
while(true){
this.ac.printValue();
}
}
}
And finally:
public class BClass extends Thread{
private Monitor ac;
public BClass(Monitor ac) {
this.ac = ac;
}
#Override
public void run() {
int v = 0;
while(true){
this.ac.changeValue(v);
v++; // this sum is not secure, if you want to print an
// ascending order, the code is diferent, I will show in
// above.
}
}
Now, if you want an ordered print:
the monitor will look like:
public class Monitor {
private int value = 0;
public boolean valueHasChanged = false;
private boolean hasPrint = true;
public synchronized void changeValue(int newValue) {
this.value = newValue;
this.valueHasChanged = true;
this.notify();
}
public synchronized void changeValuePlusOne() {
while (!hasPrint) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.value++;
this.valueHasChanged = true;
this.hasPrint = false;
this.notifyAll();
}
public synchronized void printValue() {
while (!this.valueHasChanged) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.value);
this.valueHasChanged = false;
this.hasPrint = true;
this.notifyAll();
}
public static void main(String[] args) {
Monitor ac = new Monitor();
BClass t1 = new BClass(ac);
AClass t2 = new AClass(ac);
t1.start();
t2.start();
}
public int getValue() {
return this.value;
}
}
And the Threads:
public class BClass extends Thread{
private Monitor ac;
public BClass(Monitor ac) {
this.ac = ac;
}
#Override
public void run() {
while(true){
this.ac.changeValuePlusOne();
}
}
}
The other Thread look equals:
public class AClass extends Thread{
private Monitor ac;
public AClass(Monitor ac) {
this.ac = ac;
}
#Override
public void run() {
while(true){
this.ac.printValue();
}
}
}
I am trying to create a basic Semaphore implementation using Queue. The idea is, there is a database, and there are 10 writers. Writers can only write to the database in mutual exclusion. I am using Queue because I want to implement First In First Out and Last In First Out.
Using Semaphore, I can't notify a specific thread to wake up. So my idea is what I am doing is for every Writer, I create an object and tell the Writer to wait on that object. Puts that object in a queue. Then remove the object from the queue and notify the Thread that is waiting on that object. In this way, I think I can make a FIFO or LIFO implementation.
I need help on the actual code implementation:
1. I run the code below, it gave me a lot of IllegalMonitorStateException.
2. FIFO and LIFO code (my FIFO code seems incorrect, while for LIFO code, I'm thinking to use Stack instead of Queue).
public class Test {
public static void main(String [] args) {
Database db = new Database();
for (int i = 0; i < 10; i++)
(new Thread(new Writer(db))).start();
}
}
public class Writer implements Runnable {
private Database database;
public Writer(Database database) {
this.database = database;
}
public void run() {
this.database.acquireWriteLock();
this.database.write();
this.database.releaseWriteLock();
}
}
public class Database {
private Semaphore lockQueue;
public Database() {
this.lockQueue = new Semaphore();
}
public void write() {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}
public void acquireWriteLock() {
lockQueue.acquire();
}
public void releaseWriteLock() {
lockQueue.release();
}
}
import java.util.Queue;
import java.util.LinkedList;
public class Semaphore {
private Queue<Object> queue;
public Semaphore() {
this.queue = new LinkedList<Object>();
}
public synchronized void acquire() {
Object object = new Object();
try {
if (this.queue.size() > 0) {
object.wait();
this.queue.add(object);
}
} catch (InterruptedException ie) {}
this.queue.add(object);
}
public synchronized void release() {
Object object = this.queue.remove();
object.notify();
}
}
You need to acquire the lock of the object before you can use wait() and notify().
Try to check if the following code will work:
public class Semaphore {
private Queue<Object> queue;
private int state;
public Semaphore() {
this.queue = new LinkedList<Object>();
}
public void acquire() {
Object object = new Object();
synchronized (object) {
try {
if (this.state > 0) {
this.queue.add(object);
object.wait();
} else {
state++;
}
} catch (InterruptedException ie) {
}
}
}
public void release() {
Object object = this.queue.poll();
state--;
if(null == object) {
return;
}
synchronized (object) {
object.notify();
}
}
}
In the following code fragment I'm using a semaphore to synchronize access to certain resources.
public void m () {
permit.acquire ();
while (!canFoo ()) {
permit.release ();
reticulateSpines ();
permit.acquire ();
}
doFoo ();
permit.release ();
}
It might be reasonable to enclose the acquire/release cycles in a try/finally. How can I do this, given the presence of the while loop?
On the principle of every acquire must be released I would suggest:
private final Semaphore permit = new Semaphore(8, true);
private final Random random = new Random();
private boolean canFoo() {
return random.nextBoolean();
}
private void doFoo() {
System.out.println("Foo done!");
}
private void reticulateSpines() {
System.out.println("Spines reticulated!");
}
public void m() throws InterruptedException {
permit.acquire();
try {
while (!canFoo()) {
permit.release();
try {
reticulateSpines ();
} finally {
permit.acquire();
}
}
doFoo();
} finally {
permit.release();
}
}
However - I am not sure of you are using Semaphores as they are intended. It looks much more like you are looking for something like ReentrantLock which would eliminate spinlock loop.
ReadWriteLock fooLock = new ReentrantReadWriteLock();
Lock fooReadLock = fooLock.readLock();
Lock fooWriteLock = fooLock.writeLock();
public void n() throws InterruptedException {
fooWriteLock.lock();
try {
doFoo();
} finally {
fooWriteLock.unlock();
}
}
or even perhaps
public void o() throws InterruptedException {
while (!fooWriteLock.tryLock()) {
reticulateSpines();
}
try {
doFoo();
} finally {
fooWriteLock.unlock();
}
}