By Java source code we have that
// variable not written or updated anywhere on this class
private volatile int threadStatus = 0;
public State getState() {
// get current thread state
return sun.misc.VM.toThreadState(threadStatus);
}
How and where is threadStatus updated?
The idea would be to eventually try to weave around updating methods with AOP and have a callback on threadStatus changes.
In OpenJDK source code in file hotspot/src/share/vm/classfile/javaClasses.cpp you can see following code:
// Write the thread status value to threadStatus field in java.lang.Thread java class.
void java_lang_Thread::set_thread_status(oop java_thread,
java_lang_Thread::ThreadStatus status) {
// The threadStatus is only present starting in 1.5
if (_thread_status_offset > 0) {
java_thread->int_field_put(_thread_status_offset, status);
}
}
It looks like state is managed in native code. It means that you can't intercept its change from java code.
This is an internal thread status that should reflect Thread State as NEW, RUNNABLE,..
I found a Netbeans issue that suggest that toThreadState() is/can be implemented outside JDK code:
bugfix #262633, toThreadState() implemented locally, do not rely on JDK
So possibly also modifying threadStatus not updated in Java code, Notice 0 value stand for NEW thread status:
/** taken from sun.misc.VM
*
* Returns Thread.State for the given threadStatus
*/
private static Thread.State toThreadState(int threadStatus) {
if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
return State.RUNNABLE;
} else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
return State.BLOCKED;
} else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
return State.WAITING;
} else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
return State.TIMED_WAITING;
} else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
return State.TERMINATED;
} else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
return State.NEW;
} else {
return State.RUNNABLE;
}
}
Related
Before dismissing this, it is possible to implement double checked locking without volatile, see below. I'm suggesting a variation on this, that gets rid of the local variable.
The following is a correct implementation of double checked locking from Shipilev:
public class FinalWrapperFactory {
private FinalWrapper wrapper;
public Singleton get() {
FinalWrapper w = wrapper;
if (w == null) { // check 1
synchronized(this) {
w = wrapper;
if (w == null) { // check2
w = new FinalWrapper(new Singleton());
wrapper = w;
}
}
}
return w.instance;
}
private static class FinalWrapper {
public final Singleton instance;
public FinalWrapper(Singleton instance) {
this.instance = instance;
}
}
}
I wonder if it would be possible to get rid of the local variable w:
public class FinalWrapperFactory {
private FinalWrapper wrapper; //same as example above
public Singleton get() {
if (wrapper == null) { // read 1
synchronized(this) {
if (wrapper == null) { // read 2
wrapper = new FinalWrapper(new Singleton());
return wrapper.instance; // read 3
} else {
return wrapper.instance; // read 4
}
}
} else {
return wrapper.instance; // read 5 (last read). Can this be reordered?
}
}
}
In 17.4.8. Executions and Causality Requirements of the JLS 8 it is written:
Informally, we allow an action to be committed early if we know that
the action can occur without assuming some data race occurs.
The big question here is if the last read (read 5) can be reordered so that we could potentially see a non-null wrapper in read 1 and still see a null in the last read. This should not be allowed to happen in the first invocation of get() by a thread because then the only way for the last read to occur would be because of a data race and the JMM would prohibit the reordering.
In subsequent invocations of get() reordering would be allowed but then it shouldn't matter because wrapper should be visible anyways.
My problem is, that I want to return an Object from the ArrayList "blocks".
My code doesn't work - error says This method must return a result of type block
public block getBlockUnderneath (int x, int y){
for(int i = 0; i<blocks.size(); i++){
if (blocks.get(i).x == x) {
return blocks.get(i);
}
}
}
You have two issues:
If blocks.size()==0 your method returns nothing
If none of the blocks in blocks have block.x==x your method returns nothing.
In Java a method must return a value of it is declared to do so.
The easiest solution to your issue is to return null at the end of the method:
public block getBlockUnderneath (int x, int y){
for(final block b : blocks){
if (b.x == x) {
return b;
}
}
return null;
}
Notice this uses an enhanced-for-loop, this is the recommended way to loop over Collections (or anything that implements Iterable<T>) in Java.
A better approach might be to throw an exception if no item is found:
public block getBlockUnderneath (int x, int y){
for(final block b : blocks){
if (b.x == x) {
return b;
}
}
throw new NoSuchElementException();
}
In either case you would need to handle the corner case in code that calls this method.
P.S. please stick to Java naming conventions. Classes should be in PascalCase - so you block class should be called Block.
Just for fun, in Java 8:
public block getBlockUnderneath(int x, int y) {
return blocks.stream().filter((b) -> b.x == x).findFirst().get();
}
The problem with your method is that there exists a scenario in which the return block is not executed. In that case, when a method is not declared to be void, you must declare the exit point for it.
You can exit using return or throw an exception. The choice depends on what your program should do if the requested value could not be found.
public block getBlockUnderneath (int x, int y){
for(int i = 0; i<blocks.size(); i++){
if (blocks.get(i).x == x) {
return blocks.get(i);
}
}
return null; //or throw NoSuchElementException or IllegalStateException
}
What's more you can improve you code by using a for-each loop. This solution may give you better performance and also code security as it uses an iterator rather than accessing item by index which is not necessarily efficient.
In this case you access the same item twice.
if (blocks.get(i).x == x) {
return blocks.get(i);
}
Full example
public Block findBlock(int x} { //The class name is Block
for(Block block : blocks) {
if(block.x == x {
return block;
}
}
return null;
}
Be also aware of that returning null may cause problems and thus is considered bad practice. You can avoid null, thanks to checked exceptions, default values or using Null object
There is a native implementation of this common coding pattern in Java 8. Using the Optional<T> class from the Guava library can solve this problem for versions of Java < 8.
public Optional<Block> findBlock(int x} { //The class name is Block
for(Block block : blocks) {
if(block.x == x {
return Optional.of(block);
}
}
return Optional.empty();
}
Usage
public void someActionWithBlocK() {
Optional<Block> block = findBlock(5);
if(block.isPresent()) {
//some action with block
}
}
You could never loop.
If you have a return statement inside of a loop, then the compiler doesn't take the bonafide guarantee that the loop will execute and that you will return. To get around that, you must also return after your loop.
Or, better yet, have one variable to return, like such:
block ret = null;
for(block b : blocks) {
if(b.x == x) { // I'm going to go over this in a mo
ret = b;
break;
}
}
return ret;
I'm trying to write an algorithm, that downloads a video live stream. Specifically, the respective stream I'm trying to fetch is based on a dynamic .m3u8 playlist file, which periodically provides URIs of new video files. The main goal is to combine those individual media files into one coherent InputStream.
I actually succeeded in getting it to work: I periodically check for new media files, that appear inside the playlist, and pass their HTTP streams to a custom InputStream implementation, namely InputStreamChain. Since it's a live stream, I assume it to be endless, at least for the time being. Ergo, I wanted my InputStreamChain's read() never to send the -1. Unfortunately, it did; every time when all queued media streams were consumed, the InputStreamChain ended. Instead, I wanted it to block I/O, until a new media file arrives.
So, I came up with a working solution: I adjusted the read() method to loop until there's a new stream available (a TimerTask will provide the new files). In the loop, I built in a Thread.sleep(), in order to reduce the CPU load:
public int read() throws IOException {
int bit = current.read();
if (bit == -1 && streams.size() > 0) {
// left out due to lacking relevance
} else if(bit == -1 && streams.size() == 0) {
while(streams.size() == 0) {
Thread.currentThread().sleep(50);
}
return read();
}
return bit;
}
Although it seems to work, I have a feeling, that I'm not doing it how I'm supposed to. I also tried using Lock together with Condition.await(), but when my TimerTask tried to trigger Condition.signal(), it just threw a IllegalMonitorStateException.
That's why I'm asking the question:
In what way should I delay/block an InputStream's read() method, especially in my scenario?
Edit:
For the sake of completeness, I'm going to provide my failed Lock approach, too:
private ReentrantLock ioLock;
private Condition ioCond;
private boolean waitingForStream = false;
public InputStreamChain() {
ioLock = new ReentrantLock();
ioCond = ioLock.newCondition();
}
public synchronized InputStreamChain addInputStream(final InputStream stream) {
streams.addLast(stream);
if (current == null) {
current = streams.removeFirst();
}
if(waitingForStream) {
ioCond.signal();
}
return this;
}
public int read() throws IOException {
int bit = current.read();
if (bit == -1 && streams.size() > 0) {
// do stuff
} else if(bit == -1) {
waitingForStream = true;
ioLock.lock();
try {
ioCond.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
waitingForStream = false;
ioLock.unlock();
}
return read();
}
return bit;
}
Probably you are not using synchronized block. Here is an example:
class MyReader
{
public int read() throws IOException {
int bit = current.read();
if (bit == -1 && streams.size() > 0) {
// left out due to lacking relevance
} else if(bit == -1 && streams.size() == 0) {
waitForNextStream();
return read();
}
return bit;
}
private synchronized void waitForNextStream()
{
// TODO add close handling, set current here
while (streams.isEmpty())
{
wait();
}
}
public synchronized void addNextStream(InputStream is)
{
streams.add(is);
notify();
}
}
I have a history in programming, but not much in software development. I'm currently writing a piece of software for the company I work at, and I've come to challenge myself on the readability of my code.
I want to know whether this is a "valid" alternative to embedded if statements, or if there is anything better I could use.
Let's say I have the following method:
public void someMethod()
{
if (some condition)
{
if (some condition 2)
{
if (some condition 3)
{
// ...etc all the way until:
doSomething();
}
else
{
System.err.println("Specific Condition 3 Error");
}
}
else
{
System.err.println("Specific Condition 2 Error");
}
}
else
{
System.err.println("Specific Condition 1 Error");
}
}
Now the first thing I should point out is that in this instance, combining the conditions (with &&) isn't possible, since each one has a unique error that I want to report, and if I combined them I wouldn't be able to do that (or would I?). The second thing I should point out before anyone screams "SWITCH STATEMENT!" at me is that not all of these conditions can be handled by a switch statement; some are Object specific method calls, some are integer comparisons, etc.
That said, is the following a valid way of making the above code more readable, or is there a better way of doing it?
public void someMethod()
{
if (!some condition)
{
System.err.println("Specific Condition 1 Error");
return;
}
if (!some condition 2)
{
System.err.println("Specific Condition 2 Error");
return;
}
if (!some condition 3)
{
System.err.println("Specific Condition 3 Error");
return;
}
doSomething();
}
So basically, instead of checking for conditions and reporting errors in else blocks, we check for the inverse of the condition and return if it is true. The result should be the same, but is there a better way of handling this?
If I was being particularly pedantic I would use something like this.
boolean c1, c2, c3;
public void someMethod() {
boolean ok = true;
String err = "";
if (ok && !(ok &= c1)) {
err = "Specific Condition 1 Error";
}
if (ok && !(ok &= c2)) {
err = "Specific Condition 2 Error";
}
if (ok && !(ok &= c3)) {
err = "Specific Condition 3 Error";
}
if ( ok ) {
doSomething();
} else {
System.out.print(err);
}
}
You are now single-exit AND flat.
Added
If &= is difficult for you, use something like:
if (ok && !c3) {
err = "Specific Condition 3 Error";
ok = false;
}
I would write it as
if (failing condition) {
System.err.println("Specific Condition 1 Error");
} else {
somethingExpensiveCondition2and3Dependon();
if (failing condition 2)
System.err.println("Specific Condition 2 Error");
else if (failing condition 3)
System.err.println("Specific Condition 3 Error");
else
doSomething();
}
yes, your code in both cases smells of conditional complexity (code smells)
Java is an OOP language, so your code should be factored to in the spirit of OOD, something like this:
for (Condition cond : conditions) {
if (cond.happens(params))
cond.getHandler().handle(params);
}
conditions list should be injected to this class, this way when a new condition is added or removed the class doesn't change. (open close principle)
Your second approach is fairly good. If you want something a little more baroque, you can move your conditions into Callable objects. Each object can also be provided with a way of handling errors. This lets you write an arbitrarily long series of tests without sacrificing functionality.
class Test {
private final Callable<Boolean> test;
private final Runnable errorHandler;
public Test(Callable<Boolean> test, Runnable handler) {
this.test = test;
errorHandler = handler;
}
public boolean runTest() {
if (test.call()) {
return true;
}
errorHandler.run();
return false;
}
}
You could then organize your code as follows:
ArrayList<Test> tests;
public void someMethod() {
for (Test test : tests) {
if (!test.runTest()) {
return;
}
}
doSomething();
}
EDIT
Here's a more general version of the above. It should handle almost any case of this type.
public class Condition {
private final Callable<Boolean> test;
private final Runnable passHandler;
private final Runnable failHandler;
public Condition(Callable<Boolean> test,
Runnable passHandler, Runnable failHandler)
{
this.test = test;
this.passHandler = passHandler;
this.failHandler = failHandler;
}
public boolean check() {
if (test.call()) {
if (passHandler != null) {
passHandler.run();
}
return true;
}
if (errorHandler != null) {
errorHandler.run();
}
return false;
}
}
public class ConditionalAction {
private final ArrayList<Condition> conditions;
private final Runnable action;
public ConditionalAction(ArrayList<Condition> conditions,
Runnable action)
{
this.conditions = conditions;
this.action = action;
}
public boolean attemptAction() {
for (Condition condition : conditions) {
if (!condition.check()) {
return false;
}
}
action.run();
return true;
}
}
One might be tempted to add some sort of generic data that could be passed around to share info or collect results. Rather than doing that, I'd recommend implementing such data sharing within the objects that implement the conditions and action, and leave this structure as is.
For this case, that's about as clean as you are going to get it, since you have both custom criteria and custom responses to each condition.
What you are in essence doing is validating some conditions before calling the doSomething() method. I would extract the validation into a separate method.
public void someMethod() {
if (isValid()) {
doSomething();
}
}
private boolean isValid() {
if (!condition1) {
System.err.println("Specific Condition 1 Error");
return false;
}
if (!condition2) {
System.err.println("Specific Condition 2 Error");
return false;
}
if (!condition3) {
System.err.println("Specific Condition 3 Error");
return false;
}
return true;
}
Nope, that's about what you get in Java. If you have too many of these, it may indicate that you should refactor a bit, and possibly even rethink your algorithm -- it may be worthwhile trying to simplify it a bit, because otherwise you're going to come back to the code in a few months and wonder why the heck a + b + c + d = e but a + b' + c + d = zebra
The second option you have is the more readable one. While multiple returns are usually not recommended putting all of them at the beginning of the code is clear (it isn't as if they are scattered all over the method). Nested ifs on the other hand, are hard to follow and understand.
Is there anyway in Java to find out if the given path is absolute or not regardless of the platform the program is currently running. So, what I want is probably something like the following example:
On Linux:
new File("/home/").isAbsolute() // Should return true.
new File("C:/My Documents").isAbsolute() // Should *also* return true.
On Windows:
new File("C:/Documents").isAbsolute() // Should return true.
new File("/home/").isAbsolute() // Should *also* return true.
I can probably code something to get around with this, but I just wanted to find out if anyone knew a built-in class provided in Java to solve this problem. Or has anyone ever come this problem? And how did you solve it?
Thanks!
Nope.
There are some underlying FileSystem classes (that's Java 7, but they exist prior to it as well) that expose isAbsolute(), but they're not public - so you shouldn't use them, and even if you did your code would be full of reflection junk - and only the "correct" OS ones are included in the JRE, so you'd have to code around them anyway.
Here are the Java 7 implementations of isAbsolute(...) to get you started. Note that File.getPrefixLength() is package-private.
Win32FileSystem:
public boolean isAbsolute(File f)
{
int pl = f.getPrefixLength();
return (((pl == 2) && (f.getPath().charAt(0) == slash))
|| (pl == 3));
}
UnixFileSystem:
public boolean isAbsolute(File f)
{
return (f.getPrefixLength() != 0);
}
In Java 7:
new File(path).isAbsolute()
My crack at this using Apache FilenameUtil -
public static boolean isAbsolute(final String path) {
return FilenameUtils.getPrefixLength(path) != 0;
}
Technically this is returning !relative. Which is fine for my purposes.
I ended up using this (in Java 6):
private static boolean testPath(String path) {
int prefixLen = FilenameUtils.getPrefixLength(path);
if (testPathWin(path, prefixLen) || testPathLinux(prefixLen))
return true;
else
return false;
}
private static boolean testPathWin(String path, int prefixLen) {
if (prefixLen == 3)
return true;
File f = new File(path);
if ((prefixLen == 2) && (f.getPath().charAt(0) == '/'))
return true;
return false;
}
private static boolean testPathLinux(int prefixLen) {
return (prefixLen != 0);
}