How can I determine whether a method is running in another method? - java

How can I determine whether a method is running in another method ?
This is my way.
However, there may be some performance problems.
public class Main {
public static final ThreadLocal<Object> THREAD_LOCAL = new ThreadLocal<>();
public static void main(String[] args) {
f1();
foo(i -> f1());
}
public static void f1() {
Object o = THREAD_LOCAL.get();
if (o == null) {
System.out.println("not in foo");
} else {
System.out.println("in foo");
}
}
public static void foo(Handler<Integer> handler) {
new Thread(() -> {
THREAD_LOCAL.set(new Object());
handler.handle(10);
}).start();
}
public interface Handler<A> {
void handle(A a);
}
}
Is there a better way?
Do not use threads ?

Related

Critical sections - Thinking in Java example

I read now book Thinking in Java, chapter about critical sections and I cannot understand an example, because I got exceptions which are not described in the book. An example looks like below:
class Pair {
private int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public Pair() {
this(0, 0);
}
public int getX() { return x; }
public int getY() { return y; }
public void incrementX() { x++; }
public void incrementY() { y++; }
public class PairValuesNotEqualException extends RuntimeException {
public PairValuesNotEqualException() {
super("Values are not equal: " + Pair.this);
}
}
public void checkState() {
if (x != y) {
throw new PairValuesNotEqualException();
}
}
}
abstract class PairManager {
AtomicInteger checkCounter = new AtomicInteger(0);
protected Pair p = new Pair();
public synchronized Pair getPair() {
// Make copies to protect the original
return new Pair(p.getX(), p.getY());
}
public abstract void increment();
}
// synchronization of the whole method
class PairManager1 extends PairManager {
#Override
public synchronized void increment() {
p.incrementX();
p.incrementY();
}
}
// Critical section
class PairManager2 extends PairManager {
#Override
public void increment() {
synchronized (this) {
p.incrementX();
p.incrementY();
}
}
}
class PairManipulator implements Runnable {
private PairManager pairManager;
public PairManipulator(PairManager pairManager) {
this.pairManager = pairManager;
}
#Override
public void run() {
while (true)
pairManager.increment();
}
}
class PairChecker implements Runnable {
private PairManager pairManager;
public PairChecker(PairManager pairManager) {
this.pairManager = pairManager;
}
#Override
public void run() {
while (true) {
pairManager.checkCounter.incrementAndGet();
pairManager.getPair().checkState();
}
}
}
public class CriticalSection {
static void testApproaches(PairManager pman1, PairManager pman2) {
ExecutorService exec = Executors.newCachedThreadPool();
PairManipulator
pm1 = new PairManipulator(pman1),
pm2 = new PairManipulator(pman2);
PairChecker
pcheck1 = new PairChecker(pman1),
pcheck2 = new PairChecker(pman2);
exec.execute(pm1);
exec.execute(pm2);
exec.execute(pcheck1);
exec.execute(pcheck2);
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}
System.out.println("pm1: " + pm1 + "\npm2: " + pm2);
System.exit(0);
}
public static void main(String[] args) {
PairManager
pman1 = new PairManager1(),
pman2 = new PairManager2();
testApproaches(pman1, pman2);
}
}
An example output:
pm1: Pair: Pair{x=364, y=364} counter = 471421
pm2: Pair: Pair{x=365, y=365} counter = 1015604598
This example executed without exception.
In above example I understand how does it work but the problem is in example with explicit locks.
Example with explicit lock from book:
class ExplicitPairManager1 extends PairManager {
private Lock lock = new ReentrantLock();
// why synchronized ??
public synchronized void increment() {
lock.lock();
try {
p.incrementX();
p.incrementY();
} finally {
lock.unlock();
}
}
}
class ExplicitPairManager2 extends PairManager {
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
p.incrementX();
p.incrementY();
} finally {
lock.unlock();
}
}
}
public class ExplicitCriticalSection {
public static void main(String[] args) throws Exception {
PairManager
pm1 = new ExplicitPairManager1(),
pm2 = new ExplicitPairManager2();
CriticalSection.testApproaches(pm1, pm2);
}
}
Output:
Exception in thread "pool-1-thread-4" critical.sections.Pair$PairValuesNotEqualException: Values are not equal: Pair{x=2, y=1}
at critical.sections.Pair.checkState(CriticalSection.java:49)
at critical.sections.PairChecker.run(CriticalSection.java:133)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
pm1: Pair: Pair{x=1024, y=1024} counter = 3
pm2: Pair: Pair{x=1025, y=1025} counter = 1499445
First what I don't understand why author use synchronized in ExplicitPairManager1#increment if he use also Lock object? Is that the mistake in the book?
Second problem is that I don't understand why I got exception?
Excpetion was thrown in:
class PairChecker implements Runnable {
private PairManager pairManager;
public PairChecker(PairManager pairManager) {
this.pairManager = pairManager;
}
#Override
public void run() {
while (true) {
pairManager.checkCounter.incrementAndGet();
pairManager.getPair().checkState(); // here was thrown an exception
}
}
}
Why I got excpetions and author dont? Is that possible JVM behavior is different on different systems? I use Ubuntu 16.04 LTS and Java 8.
You need to synchronize on the same object if you want to establish a critical section for multiple threads.
Your exception is getting thrown for pair modified in ExplicitPairManager2.
Let's see how possible exception-causing flow looks like:
ExplicitPairManager2.lock.lock() gets acquired
ExplicitPairManager2.p.incrementX() happens
PairChecker calls getPair()
PairChecker acquires pairManager's internal (this) monitor, but it is different than ExplicitPairManager2.lock
the result of getPair() therefore has x != y
so in the end there is no critical section.
In other words, while modifying, you were using two different objects to synchronize:
ExplicitPairManager2.lock to write
internal monitor of ExplicitPairManager2 (this) to create a copy for checking state

Understanding Runnable in Android

I was going through Handlers, the post method in it accepts a parameter of type Runnable. There's a following code snippet I came across
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
timeView.clearComposingText();
Integer hours = seconds/3600;
Integer minutes = (seconds % 3600)/60;
Integer secs = seconds % 60;
String time = String.format("%d:%02d:%02d",hours,minutes,secs);
timeView.setText(time);
if(running)
{
seconds++;
}
handler.postDelayed(this,1000);
}
});
Now since Runnable is an Interface in Java, how are we able to create a new instance of Runnable directly?
Anonymous classes can implement interfaces, and that's the only time you'll see a class implementing an interface without the "implements" keyword.
A complete example might look like:
public class MyClass {
public interface A {
void foo();
}
public interface B {
void bar();
}
public interface C extends A, B {
void baz();
}
public void doIt(C c) {
c.foo();
c.bar();
c.baz();
}
public static void main(String[] args) {
MyClass mc = new MyClass();
mc.doIt(new C() {
#Override
public void foo() {
System.out.println("foo()");
}
#Override
public void bar() {
System.out.println("bar()");
}
#Override
public void baz() {
System.out.println("baz()");
}
});
}
}
The output of this example is:
foo()
bar()
baz()

How can I safely use semaphores in a while loop?

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();
}
}

How to run two classes in parallel using multithreading?

I am working on a project in which I have multiple interface and two Implementations classes which needs to implement these two interfaces.
Suppose my first Interface is -
public Interface interfaceA {
public String abc() throws Exception;
}
And its implementation is -
public class TestA implements interfaceA {
// abc method
}
I am calling it like this -
TestA testA = new TestA();
testA.abc();
Now my second interface is -
public Interface interfaceB {
public String xyz() throws Exception;
}
And its implementation is -
public class TestB implements interfaceB {
// xyz method
}
I am calling it like this -
TestB testB = new TestB();
testB.xyz();
Problem Statement:-
Now my question is - Is there any way, I can execute these two implementation classes in parallel? I don't want to run it in sequential.
Meaning, I want to run TestA and TestB implementation in parallel? Is this possible to do?
Sure it is possible. You have actually many options. Preferred one is using callable and executors.
final ExecutorService executorService = Executors.newFixedThreadPool(2);
final ArrayList<Callable<String>> tasks = Lists.newArrayList(
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testA.abc();
}
},
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testB.xyz();
}
}
);
executorService.invokeAll(tasks);
This method gives you opportunity to get a result from executions of your tasks. InvokeAll returns a list of Future objects.
final List<Future<String>> futures = executorService.invokeAll(tasks);
for (Future<String> future : futures)
{
final String resultOfTask = future.get();
System.out.println(resultOfTask);
}
You can make your code easier to use if you make your classes implements Callable, then you will reduce amount of code needed to prepare list of tasks. Let's use TestB class as an example:
public interface interfaceB {
String xyz() throws Exception;
}
public class TestB implements interfaceB, Callable<String>{
#Override
public String xyz() throws Exception
{
//do something
return "xyz";
}
#Override
public String call() throws Exception
{
return xyz();
}
}
Then you will need just
Lists.newArrayList(new TestB(), new TestA());
instead of
final ArrayList<Callable<String>> tasks = Lists.newArrayList(
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testA.abc();
}
},
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testB.xyz();
}
}
);
Whats more, executors gives you power to maintain and reuse Thread objects which is good from performance and maintainability perspective.
Create Two Thread and run two implementation parallely. Code snippet -
ThreadA{
public void run(){
TestA testA = new TestA();
testA.abc();
}
}
...
ThreadB{
public void run(){
TestB testB = new TestB();
testB.xyz();
}
}
Start this two thread from main method -
public static void main(String[] args){
new ThreadA().start();
new ThreadB().start();
}
Try this one
Collect all the classes of same interface and call them in Multi threading.
Use Callback mechanism to get the result back
import java.util.ArrayList;
import java.util.List;
public class Demo123 {
public static void main(String[] args) {
List<InterfaceA> a = new ArrayList<InterfaceA>();
List<InterfaceB> b = new ArrayList<InterfaceB>();
TestA testA = new TestA();
TestB testB = new TestB();
a.add(testA);
b.add(testB);
for (final InterfaceA i : a) {
new Thread(new Runnable() {
#Override
public void run() {
try {
i.callback(i.abc());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
for (final InterfaceB i : b) {
new Thread(new Runnable() {
#Override
public void run() {
try {
i.callback(i.xyz());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}
interface MyCallback {
public void callback(String value);
}
interface InterfaceA extends MyCallback {
public String abc() throws Exception;
}
class TestA implements InterfaceA {
#Override
public String abc() throws Exception {
return "abc";
}
#Override
public void callback(String value) {
System.out.println("value returned:" + value);
}
}
interface InterfaceB extends MyCallback {
public String xyz() throws Exception;
}
class TestB implements InterfaceB {
#Override
public String xyz() throws Exception {
return "xyz";
}
#Override
public void callback(String value) {
System.out.println("value returned:" + value);
}
}
You may try it like this:
public static void main(String[] args) throws InterruptedException {
Executors.newCachedThreadPool().invokeAll(Arrays.asList(
new Callable<String>() {
#Override public String call() { return new TestA().abc(); }
},
new Callable<String>() {
#Override public String call() { return new TestB().xyz(); }
}));
}
public interface InterfaceA {
public String abc() throws Exception;
}
public interface InterfaceB {
public String xyz() throws Exception;
}
class TestA implements InterfaceA {
#Override public String abc() {
System.out.println("Inside A"); return null;
}
}
class TestB implements InterfaceB {
#Override public String xyz() {
System.out.println("Inside B"); return null;
}
}

Java - Using a static list from another class

I have a class like this , where I am updating a static variable in a thread. And I need to access this variable from another class.
import java.util.ArrayList;
import java.util.List;
public class VariableUpdater implements Runnable {
static List < String > abc = new ArrayList < String > ();
private static VariableUpdater instance = null;
private VariableUpdater() {}
public static synchronized VariableUpdater getInstance() {
if (instance == null) {
instance = new VariableUpdater();
}
return instance;
}
public static void main(String[] args) {
Thread th = new Thread( VariableUpdater.getInstance());
th.start();
}
#Override
public void run() {
while (true) {
System.out.println();
try {
abc.add("aa");
Thread.sleep(1000);
printContent();
} catch (Exception e) {
// TODO: handle exception
}
}
}
public synchronized void printContent() {
for (String string: abc) {
System.out.println(string);
}
}
}
And this variable needs to be accessed from another class like this :
public class Accessor {
public static void main(String[] args) {
VariableUpdater.getInstance().printContent();
}
}
The problem is, when running the Accessor class the list is empty.
Am I missing something here?
UPDATE/Solution
It turns out we can achieve this by using Hazelcast or some sort of messaging/caching utility. I will post a full solution soon.
Source: How to share object between java applications?
From this code u can access the List in another class object
import java.util.ArrayList;
import java.util.List;
public class VariableUpdater implements Runnable {
static List < String > abc = new ArrayList < String > ();
private static VariableUpdater instance = null;
private VariableUpdater() {}
public static synchronized VariableUpdater getInstance() {
if (instance == null) {
instance = new VariableUpdater();
}
return instance;
}
public static void main(String[] args) {
Thread th = new Thread(new VariableUpdater());
th.start();
Accessor.print();
}
#Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println();
try {
abc.add("aa");
// Thread.sleep(1000);
//printContent();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public synchronized void printContent() {
System.out.println("List :: " + abc);
}
}
class Accessor {
public static void print() {
System.out.println("Accessor");
VariableUpdater.getInstance().printContent();
}
}
You have two main() methods in two different classes. On running two main() methods there will be two instances of JVM and those do not share anything. So your list will always be empty.
Use one main() method to start threads.
public class Main{
//shared state
public static void main(String[] args){
VariableUpdator variableUpdatorInstance = ...
Accessor accessorInstance = ...
variableUpdatorInstance.start();
accessorInstance.start();
//or in your case
new Thread(new VariableUpdater()).start();
Thread.sleep(9000); //runs eventually after 9 seconds
Accessor.print();
}
}
UPDATE:
class Thread1 extends Thread{
static List<String> list = new ArrayList<String>();
}
class OtherClass{
public void someMethod(){
Thread1.list; //this is how you access static variable of one class in other
}
}

Categories