InnisBrendan
InnisBrendan

Reputation: 2249

Is modifying my ArrayList in runOnUiThread thread safe?

I have an Activity that holds on to an ArrayList. The Activity will modify and access the ArrayList, but I would also like to access it from other Threads.

I am using runOnUiThread to accomplish this, but I am not sure if this is thread safe or not, or if there is a better way of doing this

class MainActivity : AppCompatActivity() {
    var connectedSockets = ArrayList<Socket>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val port: Int
        serverSocket = ServerSocket(0).also { socket ->
            port = socket.localPort
        }

        Thread(Runnable {
            while (serverSocket != null) {
                serverSocket?.accept()?.let {
                    runOnUiThread {
                        connectedSockets.add(it)
                    }
                }
            }
        }).start()
    }

}

Is connectedSockets thread safe in this case? Is there a more sensible way to do this or am I on the right track?

Upvotes: 0

Views: 140

Answers (3)

from56
from56

Reputation: 4127

It doesn't make sense that you create a separate thread and within the thread you force the code to be executed in the UI task. In fact you are not using multithreading

If you want to modify your ArrayList in a true separate thread and make it thread safe, create an instance like Object myObject = new Object(); and enclose any code that modifies the ArrayList inside this synchronize(myObject) {/ ** code that alters the list ** /}

With this, only one task can modify the list at a time

Upvotes: 0

Alexey Soshin
Alexey Soshin

Reputation: 17721

This code is not thread-safe for a number of reasons.

  1. connectedSockets is public and mutable. You can change it to:

    private val connectedSockets = ArrayList<Socket>()

  2. ArrayList by itself is not thread safe. And Vector is deprecated. You can use CopyOnWriteArrayList, though.

    private val connectedSockets = CopyOnWriteArrayList<Socket>()

Upvotes: 0

gromyk
gromyk

Reputation: 610

It is safe unless you start to modify List from two different threads or whatever else that is not thread-safe. For such cases you must have only one thread where something will be modified from. If you will take something from the list and put something there from the same thread, then you'll prevent a situation with concurrent modification.

Upvotes: 2

Related Questions